Permalink
Browse files

Direct name association

  • Loading branch information...
jmonteiro committed Oct 6, 2012
1 parent 43aff07 commit 910e59eb1d1820350f2d857105251bf79f51afe1
Showing with 31 additions and 1 deletion.
  1. +13 −1 lib/associations/associations.rb
  2. +18 −0 spec/associations/associations_spec.rb
@@ -6,8 +6,10 @@ module ActiveRecordExtensions
def belongs_to_active_hash(association_id, options = {})
options = {
:class_name => association_id.to_s.camelize,
- :foreign_key => association_id.to_s.foreign_key
+ :foreign_key => association_id.to_s.foreign_key,
+ :shortcuts => []
}.merge(options)
+ options[:shortcuts] = [options[:shortcuts]] unless options[:shortcuts].kind_of?(Array)
define_method(association_id) do
options[:class_name].constantize.find_by_id(send(options[:foreign_key]))
@@ -17,6 +19,16 @@ def belongs_to_active_hash(association_id, options = {})
send "#{options[:foreign_key]}=", new_value ? new_value.id : nil
end
+ options[:shortcuts].each do |shortcut|
+ define_method("#{association_id}_#{shortcut}") do
+ send(association_id).try(shortcut)
+ end
+
+ define_method("#{association_id}_#{shortcut}=") do |new_value|
+ send "#{association_id}=", new_value ? options[:class_name].constantize.send("find_by_#{shortcut}", new_value) : nil
+ end
+ end
+
create_reflection(
:belongs_to,
association_id.to_sym,
@@ -123,6 +123,24 @@ class Book < ActiveRecord::Base
school.city.should == city
end
+ it "is assignable by name attribute" do
+ School.belongs_to_active_hash :city, :shortcuts => [:name]
+ City.data = [ {:id => 1, :name => 'gothan'} ]
+ city = City.find_by_name 'gothan'
+ school = School.create :city_name => 'gothan'
+ school.city.should == city
+ school.city_name.should == 'gothan'
+ end
+
+ it "have custom shortcut" do
+ School.belongs_to_active_hash :city, :shortcuts => :friendly_name
+ City.data = [ {:id => 1, :friendly_name => 'Gothan City'} ]
+ city = City.find_by_friendly_name 'Gothan City'
+ school = School.create :city_friendly_name => 'Gothan City'
+ school.city.should == city
+ school.city_friendly_name.should == 'Gothan City'
+ end
+
it "returns nil when the record does not exist" do
School.belongs_to_active_hash :city
school = School.create! :city => nil

0 comments on commit 910e59e

Please sign in to comment.