予算プランナー用の Rails 3.2 アプリがあります。
私のモデルにはユーザーがいて、ユーザーには 1 つの予算があり、各予算には多くの Budget_item があります。ユーザーが作成されると、予算が作成されます。
ユーザーが予算にアクセスするとき、何もない場合は空の Budget_item を挿入します。ただし、私がやりたいのは、推定コストを含む一連のデフォルトの予算項目を各予算に事前入力することです。これは、予算の作成時、またはユーザーが空の予算にアクセスした場合に実行できます。
Railsで「正しい方法」で物事を行おうとしているので、できるだけクリーンな実装をしたいと思います(異常なコードが見られる場合は、まだ完全ではありません:)
私のコードはここで見ることができます: https://github.com/michaelward82/WeddingPlanner
ただし、回答は迅速な回答よりも優れていると見なされます。正しい答えを与える前に、妥当な時間を与えます。
編集:
BudgetsController を次のように変更することで、デフォルト レコードの作成に成功しました。
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
これが最善の方法ですか?私はこれで満足していますが、これを整理するためのよりクリーンな方法があれば、喜んでお知らせします. 上記よりもはるかに多くのデフォルト項目があるため、私のコントローラがこのデータを保存する場所であるとは思えません。