我有一个Selection
模型,其中有许多Choices
和一个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查询的问题 –