1

fields_for を使用してネストされた属性に問題がある。私が欠けているものを知っている人はいますか?多くの投稿とRailsCastをチェックしましたが、理解できませんでした。

概要: 1 つ以上のパラメーター (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

インジケーター.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 を indicator_controller の new/create メソッドに追加すると、構築された chart_param_value レコードの数に基づいて、フォームに重複したフィールドが表示されます。

4

0 に答える 0