我有一個用於預算計劃的rails 3.2應用程序。Rails:爲has_many關係創建默認記錄
我的模型具有用戶,用戶有一個預算,每個預算有很多budget_items。創建用戶時,會爲其創建預算。
當用戶訪問他們的預算時,我插入一個空白的budget_item,如果他們沒有。但是,我想要做的是將每個預算與一組默認預算項目與預計成本一起預先填充。這可以在創建預算時完成,也可以在用戶訪問空白預算時完成。
我想作爲清潔的實現成爲可能,因爲我想,如果你看到任何不尋常的代碼:)
我的代碼可以做到在Rails的事情「正確的方式」(還沒有應用看到這裏:https://github.com/michaelward82/WeddingPlanner
那麼雖然答案會比快速答案更好。在給出正確的答案之前,我會給出合理的時間。
編輯:
class BudgetsController < ApplicationController
def show
if current_user
@budget = current_user.budget
if @budget.budget_items.empty?
set_default_budget_items @budget
end
else
redirect_to log_in_path
end
end
def update
@budget = current_user.budget
if @budget.update_attributes(params[:budget])
redirect_to budget_path, :flash => { :success => "Budget changes saved" }
else
redirect_to budget_path, :flash => { :error => "Budget changes were not saved" }
end
end
private
def set_default_budget_items(budget)
default_budget_items = [
{ "description"=>"Insurance", "estimated_cost"=>"110", "actual_cost"=>"0", "position"=>"1"},
{ "description"=>"The Service", "estimated_cost"=>"520", "actual_cost"=>"0", "position"=>"2"},
{ "description"=>"Reception (venue, food & drinks)", "estimated_cost"=>"4000", "actual_cost"=>"0", "position"=>"3"}
]
default_budget_items.each {|b| @budget.budget_items.new(b) }
end
end
這是最好的辦法:
我改變我的BudgetsController通過以下方式實現的默認記錄的創建已經succedded?我很高興與此合作,但如果有更好的方法來組織這個,那麼我很樂意知道。默認項目比上面顯示的要多得多,所以我懷疑我的控制器是數據生存的地方。
你嘗試過種子嗎?您還可以使用默認值填充seeds.rb文件 – 2012-04-23 10:36:10
創建數據庫時,這不是應該存在的數據,這是應用程序的每個新用戶對應其預算的數據。我不認爲種子會做我想要的。 – michaelward82 2012-04-23 10:38:22