我有建筑物,公寓,住宅和用户由于某种原因不能很好地在一起玩。不确定我错过了什么。
class Building < ActiveRecord::Base
attr_accessible ...
has_many :apartments, inverse_of: :building
...
end
class Apartments < ActiveRecord::Base
...
belongs_to :building, inverse_of: :apartment
has_many :residences, inverse_of: :apartment
...
end
class Residence < ActiveRecord::Base
...
belongs_to :apartment, inverse_of: :residence
belongs_to :user, inverse_of: :residence
...
end
class User < ActiveRecord::Base
...
has_many :residences, inverse_of: :user
...
end
在rails控制台中,我遇到了反关联问题:
的A.class
=&GT;公寓(id:整数,building_id:整数,...,created_at:datetime,updated_at:datetime)
a.building
ActiveRecord :: InverseOfAssociationNotFoundError:找不到构建的反向关联(:Building in Building) 来自/Users/[me]/.rvm/gems/ruby-1.9.3-p194@r3t2/gems/activerecord-3.2.8/lib/active_record/reflection.rb:246:in`check_validity_of_inverse!'
h.class
=&GT; Residence(id:integer,apartment_id:integer,user_id:integer ...,created_at:datetime,updated_at:datetime)
h.user
ActiveRecord :: InverseOfAssociationNotFoundError:无法找到用户的反向关联(:用户居住地) 来自/Users/[me]/.rvm/gems/ruby-1.9.3-p194@r3t2/gems/activerecord-3.2.8/lib/active_record/reflection.rb:246:in`check_validity_of_inverse!'
我可以继续。这些类之间的关系似乎被挂起了。我在过去的几个小时里尝试了各种迭代,但最后我称之为“ma ma!”非常感谢任何线索。
答案 0 :(得分:7)
Building
中的公寓协会是复数,因此您应添加s
:
class Apartments < ActiveRecord::Base
...
belongs_to :building, inverse_of: :apartments
has_many :residences, inverse_of: :apartment
...
end
答案 1 :(得分:1)
为什么使用:inverse_of? Rails将确定您的情况的反向关系,其中:belongs_to和:has_many声明的名称与其类匹配。