Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Comparing changes

Choose two branches to see what's changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
...
Checking mergeability… Don't worry, you can still create the pull request.
  • 2 commits
  • 2 files changed
  • 0 commit comments
  • 2 contributors
Commits on Apr 07, 2012
@kbrock add has_one to active_hash. e6be675
Commits on Apr 09, 2012
@flavorjones flavorjones Merge pull request #49 from kbrock/activehash_has_one
add has_one to active_hash.
5fce079
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

No commit comments for this range

Something went wrong with that request. Please try again.