我有一个用于预算计划的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