2016-02-04 55 views
0

我有這些模型:軌道4:指定一個關係的記錄,另一

ofert.rb

class Ofert < ActiveRecord::Base 
    has_many :purchasing_groups 
end 

purchasing_group.rb

class PurchasingGroup < ActiveRecord::Base 
    belongs_to :ofert 
    has_many :group_goals 
end 

group_goal.rb

class GroupGoal < ActiveRecord::Base 
    belongs_to :purchasing_group 
end 

在控制器動作我試圖做這樣的事情:

copy_of_last_group_goals = @ofert.purchasing_groups.last.group_goals 

@ofert.purchasing_groups.create 
#@ofert.last_purchasing_group.save! adding this, did not work 
#@ofert.save! This neither work. 
@ofert.purchasing_groups.last.group_goals = copy_or_last_group_goals 
@ofert.save 

以上的作品在本地很好,我也試過它從控制檯,它也工作。我有我的應用程序部署在PostgreSQL的Heroku的,這不是在生產工作時,它拋出這個錯誤:

ActiveRecord::RecordNotSaved (Failed to replace group_goals because one or more of the new records could not be saved): 

我試圖拯救purchasing_groups,也節省了ofert,你可以在註釋行看到,但只在我的heroku應用程序的控制檯中工作,但不是當我直接在部署的應用程序中嘗試時。

任何想法?

+0

爲什麼你只是不使用'a = @ ofert.purchasing_groups.create',然後'a.group_goals = copy_or_last_group_goals'? –

+0

有什麼區別?請幫我理解發生了什麼=( – SsouLlesS

+0

好吧,甚至複製'GroupGoal'實例也很奇怪,對於新的'PurchasingGroup',你必須創建新的組目標列表(根據你的模式),所以你不能複製數組,是因爲你有唯一的'belongs_to:purchasing_group'關係,在其他情況下,你必須將你的模式更改爲'PurchasingGroup'和'GroupGoal'之間的多對多關係 –

回答

1

根據我讀的代碼

copy_of_last_group_goals = @ofert.purchasing_groups.last.group_goals 
@ofert.purchasing_groups.create 
@ofert.purchasing_groups.last.group_goals = copy_or_last_group_goals 
@ofert.save 

你想創建一個新的purchasing_group,並與那名在purchasing_group它之前相同group_goals填充這些行?是對的嗎?

如果是這樣,那麼我會說你不能,因爲你沒有GroupGoalPurchasingGroup之間的關係has_and_belongs_to_many

+0

你能否提供一個解決方法你認爲'a = @ ofert.purchasing_groups.create',然後'a.group_goals = copy_of_last_group_goals'會使俄羅斯人在這個節目中提出的訣竅nts以上? – SsouLlesS

+0

感謝您的提示,這很有幫助,我終於發現這個技巧是使用'dup'方法,而不是將它們分配爲變量,這裏有一個要點解釋了'dup'和'clone' ActiveRecord方法https ://gist.github.com/liwh/1195027 – SsouLlesS