Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #49 from kbrock/activehash_has_one

add has_one to active_hash.
  • Loading branch information...
commit 5fce07949a10e045ae7f1927fc596eca3c44f34b 2 parents b7be46f + e6be675
@flavorjones flavorjones authored
View
16 lib/associations/associations.rb
@@ -50,6 +50,22 @@ def has_many(association_id, options = {})
end
end
+ def has_one(association_id, options = {})
+ define_method(association_id) do
+ options = {
+ :class_name => association_id.to_s.classify,
+ :foreign_key => self.class.to_s.foreign_key
+ }.merge(options)
+
+ scope = options[:class_name].constantize
+
+ if scope.respond_to?(:scoped) && options[:conditions]
+ scope = scope.scoped(:conditions => options[:conditions])
+ end
+ scope.send("find_by_#{options[:foreign_key]}", id)
+ end
+ end
+
def belongs_to(association_id, options = {})
options = {
View
36 spec/associations/associations_spec.rb
@@ -209,7 +209,43 @@ class Book < ActiveRecord::Base
author.city_id.should == @city.id
end
end
+ end
+
+ describe "#has_one" do
+ context "with ActiveRecord children" do
+ before do
+ Author.has_one :book
+ end
+
+ it "find the correct records" do
+ book = Book.create! :author_id => 1, :published => true
+ author = Author.create :id => 1
+ author.book.should == book
+ end
+
+ it "returns nil when there is no record" do
+ author = Author.create :id => 1
+ author.book.should be_nil
+ end
+ end
+ context "with ActiveHash children" do
+ before do
+ City.has_one :author
+ Author.field :city_id
+ end
+
+ it "find the correct records" do
+ city = City.create :id => 1
+ author = Author.create :city_id => 1
+ city.author.should == author
+ end
+
+ it "returns nil when there are no records" do
+ city = City.create :id => 1
+ city.author.should be_nil
+ end
+ end
end
describe "#marked_for_destruction?" do
Please sign in to comment.
Something went wrong with that request. Please try again.