當我使用has_one時,它完美地工作,但不是在has_many上。在這裏你可以看到object_id是不同的,因爲它運行另一個SQL來再次獲取它。inverse_of是否適用於has_many?
ruby-1.9.2-p290 :001 > e = Employee.create(name: 'rafael', active: false)
ruby-1.9.2-p290 :002 > b = Badge.create(number: 1, employee: e)
ruby-1.9.2-p290 :003 > a = Address.create(street: "123 Market St", city: "San Diego", employee: e)
ruby-1.9.2-p290 :004 > e = Employee.first
Employee Load (0.2ms) SELECT "employees".* FROM "employees" LIMIT 1
=> #<Employee id: 1, name: "rafael", active: false, created_at: "2011-10-04 17:09:25", updated_at: "2011-10-04 17:09:25">
ruby-1.9.2-p290 :002 > e.is_active?
=> false
ruby-1.9.2-p290 :003 > e.object_id
=> 2182895380
ruby-1.9.2-p290 :004 > e.badge.employee.is_active?
Badge Load (17.6ms) SELECT "badges".* FROM "badges" WHERE "badges"."employee_id" = 1 LIMIT 1
=> false
ruby-1.9.2-p290 :005 > e.badge.employee.object_id
=> 2182895380
ruby-1.9.2-p290 :006 > e.addresses.first.employee.is_active?
Address Load (0.2ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."employee_id" = 1 LIMIT 1
Employee Load (0.3ms) SELECT "employees".* FROM "employees" WHERE "employees"."id" = 1 LIMIT 1
=> false
ruby-1.9.2-p290 :007 > e.addresses.first.employee.object_id
Address Load (0.3ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."employee_id" = 1 LIMIT 1
Employee Load (0.2ms) SELECT "employees".* FROM "employees" WHERE "employees"."id" = 1 LIMIT 1
=> 2181302220
ruby-1.9.2-p290 :008 >
這裏是我設置用我的測試代碼:
class Employee < ActiveRecord::Base
has_many :addresses, :inverse_of => :employee
has_one :badge, :inverse_of => :employee
accepts_nested_attributes_for :addresses
accepts_nested_attributes_for :badge
# validates_associated :addresses
def is_active?
active
end
end
class Address < ActiveRecord::Base
belongs_to :employee, :inverse_of => :addresses
validates :city, length: { within: 100..1000, message: "Too short"}, :if => lambda {|a| a.employee.is_active?}
end
class Badge < ActiveRecord::Base
belongs_to :employee, :inverse_of => :badge
validates :number, length: { within: 2..10, message: "Too long"}, :if => lambda {|b| b.employee.is_active?}
end
的可能重複[ActiveRecord的:逆\ _of不工作就有\ _many:通過對上創建的連接模式(HTTP: //stackoverflow.com/questions/7436173/activerecord-inverse-of-does-not-work-on-has-many-through-on-the-join-model-on) –