2017-08-16 31 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