2017-08-16 96 views
0

我有一个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]] 
+0

基本上'selection.default_choice'总是返回'selection.choices'的第一个选项。 –

+0

你可以发布在执行'selection.default_choice'时运行的SQL查询吗? – Pavan

+0

我更新了添加SQL查询的问题 –

回答

0

您使用的是相同的模型Choice两者关系has_many :choicheshas_one :default_choice。因此,当您查询has_one :default_choice结果全部来自choices表和has_one时,您只会得到一个结果,它是查找引用到Selection对象的第一个结果。


UPDATE

要落实的has_many默认,你可以做这样的事情加上选择模型列,如果它的默认选择,这将是真实的。然后,has_one关系需要有足够的空间来获得默认为true的选择,如下所示:

has_one :default_choice, -> { where default_choice: true }, class_name: 'Choice' 
+0

这对我来说很清楚。但是,我如何设置一个特定的'default_choice'呢? –

+0

这是一个完全不同于你问的问题。 您可以执行一些操作,如在Choice上添加列,如果它是默认选择,则该列将为“true”。然后,has_one关系需要有足够的空间来获得默认为true的选择,如下所示: 'has_one:default_choice, - > {where default_choice:true},class_name:'Choice'' – meshin

相关问题