レール 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
。
これはバグですか、それとも仕様ですか?