Ruby on rails 同一模型上的多个关联
我有针对企业和用户的模型。一个企业可能有多个经理,但其中只有一个经理可以是所有者。我尝试如下建模:Ruby on rails 同一模型上的多个关联,ruby-on-rails,associations,Ruby On Rails,Associations,我有针对企业和用户的模型。一个企业可能有多个经理,但其中只有一个经理可以是所有者。我尝试如下建模: class Business < ApplicationRecord has_many :managements has_many :managers, through: :managements, source: :user, autosave: true has_one :ownership, -> { where owner: true },
class Business < ApplicationRecord
has_many :managements
has_many :managers, through: :managements, source: :user, autosave: true
has_one :ownership, -> { where owner: true },
class_name: 'Management',
autosave: true
has_one :owner, through: :ownership, source: :user, autosave: true
end
class Management < ApplicationRecord
belongs_to :user
belongs_to :business
end
class User < ApplicationRecord
has_many :managements
has_many :businesses, through: :managements
end
类业务{其中所有者:true},
类别名称:“管理”,
自动保存:正确
has_one:owner,through::owner,source::user,autosave:true
结束
班级管理<应用记录
属于:用户
属于:商业
结束
类用户<应用程序记录
有很多:管理
有很多:企业,通过::管理
结束
在我试图挽救业务之前,这一切似乎都很顺利:
business.owner = owner
#<User id: nil, email: "owner@example.com", password_digest: "$2a$04$aXswT85yAiyQ/3Pa2QAMB.4eDs9JPikpFfb8fJtwsUg...", confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, created_at: nil, updated_at: nil>
business.ownership
#<Management id: nil, user_id: nil, business_id: nil, owner: true, created_at: nil, updated_at: nil>
(byebug) business.owner
#<User id: nil, email: "owner@example.com", password_digest: "$2a$04$aXswT85yAiyQ/3Pa2QAMB.4eDs9JPikpFfb8fJtwsUg...", confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, created_at: nil, updated_at: nil>
(byebug) business.valid?
false
(byebug) business.errors
#<ActiveModel::Errors:0x007f9ef5ca5148 @base=#<Business id: nil, longitude: #<BigDecimal:7f9ef2c23e48,'0.101E3',9(27)>, latitude: #<BigDecimal:7f9ef2c23d58,'-0.23E2',9(27)>, address: "line 1, line2, town, county", postcode: "B1 1NL", business_name: "Business 1", deleted_at: nil, created_at: nil, updated_at: nil>, @messages={:"ownership.business"=>["must exist"]}, @details={:"ownership.business"=>[{:error=>:blank}]}>
business.owner=owner
#
企业所有权
#
(byebug)business.owner
#
(byebug)business.valid?
假的
(byebug)business.errors
#[“必须存在”]},@details={:“ownership.business”=>[{:error=>:blank}]>
我不明白什么是所有权.业务
关系?我能做些什么来让它工作
我使用的是rails 5.0.6。尝试将
反向::business
附加到has\u one:ownership
has_one :ownership, -> { where(owner: true) },
class_name: 'Management',
autosave: true,
inverse_of: :business
从中可以看出,的
:inverse\u选项是一种避免SQL查询的方法,而不是生成SQL查询。它提示ActiveRecord
使用已加载的数据,而不是通过关系再次获取数据
我认为当您处理尚未持久化的关联时,
的逆\u最有用
- 如果没有
参数,:inverse\u的
将返回nil,因为它会触发sql查询,并且数据尚未存储ownership.business
- 使用参数的:逆_,从内存中检索数据
业务
和所有者
都是新记录吗?试着把逆的::business
附加到的has-one:ownership
thanky-you上,这样就行了。它们都是新的记录也许你能解释为什么会这样,为什么需要它?