使用fields_for遇到嵌套属性问题。谁知道我错过了什么?我检查了很多帖子和RailsCasts,但是还没弄清楚。
概述:我有一个包含一个或多个参数(chart_param)的图表类型列表(chart_type)。根据选择的图表类型,我显示正确的图表参数,并允许用户输入值(chart_param_value)。这完全来自我的指标表格。
问题:表单提交未正确重新调整嵌套属性。提交的参数类似于“chart_param_values”=> {“value”=>“”,“chart_param_id”=>“10024”}“。
chart_type.rb
attr_accessible :multiple_indicators, :name, :chart_params_attributes
has_many :chart_params, :dependent => :destroy
accepts_nested_attributes_for :chart_params, :allow_destroy => true
def self.single_indicator
where(:multiple_indicators => false)
end
def self.multiple_indicators
where(:multiple_indicators => true)
end
chart_param.rb
attr_accessible :chart_type_id, :name, :required, :tooltip
belongs_to :chart_type
chart_param_value.rb
attr_accessible :chart_param_id, :indicator_id, :main_indicator_chart_id, :value
belongs_to :chart_param
#belongs_to :chart_type
belongs_to :indicator
indicator.rb
attr_accessible :chart_type_id, :description, :help_text, :key_name, :name, :display_screen, :any_details, :indicator_details_attributes, :chart_param_values_attributes
belongs_to :chart_type
has_many :chart_param_values, :dependent => :destroy
accepts_nested_attributes_for :chart_param_values
指标/ _form.html.erb
<%= form_for(@indicator) do |f| %>
...
<div class="field">
<%= f.label "Chart Type" %>
<%= f.select :chart_type_id, ChartType.single_indicator.collect { | ct | [ct.name, ct.id] }, {}, :onchange => "update_chart_params(this);" %>
</div>
<div id="Charts">
<% ChartType.single_indicator.each do |ct| %>
<div id="chart_type_params_<%= ct.id %>" <% if !@indicator.chart_type_id.eql?(ct.id) %> style="display: none" <% end %> >
<% ct.chart_params.each do |ctp| %>
<%= fields_for :chart_param_values do | builder | %>
<%= builder.hidden_field :chart_param_id, :value => ctp.id %>
<%= builder.label :value, ctp.required ? "* #{ctp.name}" : ctp.name %>
<%= builder.text_field :value %><br />
<% end %>
<% end %>
</div>
<% end %>
</div>
<script language="javascript">
update_chart_params = function(select){
alert(select.value);
<% ChartType.single_indicator.each do |ct| %>
$('#chart_type_params_' + <%= ct.id %>).hide();
<% end %>
$('#chart_type_params_' + select.value).show();
}
*另外,如果我将fields_for更改为f.fields_for并将@ indicator.chart_param_values.build添加到indicators_controller new / create方法,我会根据构建的chart_param_value记录数量在表单上获得重复字段。