导轨 5.1.2 红宝石 2.5.3
我知道有多种方法可以暗示这种关系,但是,这个问题更多的是关于为什么以下不起作用而不是解决现实世界的问题。
has_many
设置
class Subscriber < ApplicationRecord
has_many :subscriptions, inverse_of: :subscriber
has_many :promotions, through: :subscriptions, inverse_of: :subscriptions
accepts_nested_attributes_for :subscriptions
accepts_nested_attributes_for :promotions
end
class Subscription < ApplicationRecord
belongs_to :subscriber, inverse_of: :subscriptions
belongs_to :promotion, inverse_of: :subscriptions
end
class Promotion < ApplicationRecord
has_many :subscriptions, inverse_of: :promotion
has_many :subscribers, through: :subscriptions, inverse_of: :subscriptions
accepts_nested_attributes_for :subscriptions
accepts_nested_attributes_for :subscribers
end
在上述Subscriber
模型中,设置为使用has_many
以下关系将起作用:
s = Subscriber.new
s.subscriptions.build
# OR
s.promotions.build
在那之后,我希望在人际关系Subscriber
上表现得一样has_one
has_one
设置
class Subscriber < ApplicationRecord
has_one :subscription, inverse_of: :subscriber
has_one :promotion, through: :subscription, inverse_of: :subscriptions
accepts_nested_attributes_for :subscription
accepts_nested_attributes_for :promotion
end
class Subscription < ApplicationRecord
belongs_to :subscriber, inverse_of: :subscription
belongs_to :promotion, inverse_of: :subscriptions
end
class Promotion < ApplicationRecord
has_many :subscriptions, inverse_of: :promotion
has_many :subscribers, through: :subscriptions, inverse_of: :subscription
accepts_nested_attributes_for :subscriptions
accepts_nested_attributes_for :subscribers
end
但是,尝试promotion
使用等效的构建方法构建嵌套关联会has_one
导致NoMethodError (undefined method 'build_promotion' for #<Subscriber:0x00007f9042cbd7c8>)
错误
s = Subscriber.new
s.build_promotion
但是,这确实有效:
s = Subscriber.new
s.build_subscription
我认为人们应该期望以与构建has_one
相同的方式构建嵌套关系是合乎逻辑的has_many
。
这是一个错误还是设计使然?