私はSelection
モデルが多く、Choices
と1つはDefaultChoice
です。 このように関係が構成されています。has_oneの関係から予期せぬ結果を得る
モデル(私は間違って何かがあり、ここだと思う)
class Selection < ApplicationRecord
has_many :choices, dependent: :delete_all
has_one :default_choice, class_name: 'Choice'
end
class Choice < ApplicationRecord
belongs_to Selection
end
移行
create_table :selections do |t|
t.references :default_choice, index: true
end
create_table :choices do |t|
t.belongs_to :selection
end
どういうわけか何かが右ではありません。
# let's say:
selection = Selection.find(1)
selection.choices << Choice.find(1)
selection.choices << Choice.find(2)
selection.default_choice = Choice.find(2)
selection.save!
# then
selection.default_choice_id = 2
# but
selection.default_choice.id = 1
来る方法!
selection.default_choice
は、このクエリを生成します。
Choice Load (0.5ms) SELECT "choices".* FROM "choices" WHERE "choices"."selection_id" = $1 LIMIT $2 [["selection_id", 1], ["LIMIT", 1]]
基本的に 'selection.default_choice'は常に' selection.choices'の最初の選択肢を返します。 –
'selection.default_choice'を実行したときに実行されるSQLクエリを投稿できます – Pavan
SQLクエリを追加する質問が更新されました –