text_field の値を上書きするカスタム FormBuilder があります。
class TimesheetFormBuilder < ActionView::Helpers::FormBuilder
def text_field(method, opts)
#Get a reference to the model object
object = @template.instance_variable_get("@#{@object_name}")
value = object.send(method)
(opts ||= {}).merge!(value: value + '(foo)')
super(method, opts)
end
end
ネストされたフォームがあります。タイムシートには多くの作業ログがあります
<%= form_for @timesheet, :builder => TimesheetFormBuilder do |timesheet_form| %>
<%= timesheet_form.fields_for :worklogs do |worklog_form| %>
<%= worklog_form.text_field :monday %>
<% end %>
<% end %>
私が抱えている問題は、オブジェクトのメソッドを呼び出す方法がわからないことです。
オブジェクトを取得すると
object = @template.instance_variable_get("@#{@object_name}")
その後、エラーが発生します
`@timesheet[worklogs_attributes][0]' はインスタンス変数名として許可されていません
を解析する方法があるobject_name
ので、取得@timesheet
しworklogs
て0
実行できます
@timesheet.worklogs[0]
しかし、より良い方法はありますか?どうもありがとう