1

我的建筑物、公寓、住宅和用户由于某种原因不能很好地配合使用。不知道我错过了什么。

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 控制台中,我遇到了反向关联的问题:

一类

=> Apartment(id: integer, building_id: integer, ..., created_at: datetime, updated_at: datetime)

建筑

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!'

h.类

=> Residence(id: integer, apartment_id: integer, user_id: integer..., created_at: datetime, updated_at: datetime)

用户

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!” 将非常感谢任何线索。

4

2 回答 2

7

公寓协会Building是复数,所以你应该添加一个s

class Apartments < ActiveRecord::Base
  ...
  belongs_to :building, inverse_of: :apartments
  has_many :residences, inverse_of: :apartment
  ...
end
于 2013-05-04T20:44:03.477 回答
1

为什么还要使用:inverse_of?Rails 将为您的情况确定反向关系,其中 :belongs_to 和 :has_many 声明的名称与其类匹配。

于 2013-05-04T20:31:21.903 回答