Skip to content

Commit

Permalink
add has_one to active_hash.
Browse files Browse the repository at this point in the history
  • Loading branch information
kbrock committed Apr 7, 2012
1 parent b7be46f commit e6be675
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/associations/associations.rb
Expand Up @@ -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 = {
Expand Down
36 changes: 36 additions & 0 deletions spec/associations/associations_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit e6be675

Please sign in to comment.