Rails嵌套表单与Has_many通过关联循环

时间:2013-02-21 07:56:34

标签: ruby-on-rails-3 nested-attributes has-many-through

我正在尝试从嵌套表单创建/更新一些has_many关联详细信息。我有这3个模型PoliticianCharacteristic&并加入模型CharacteristicPoint

class Politician < ActiveRecord::Base
      has_many :characteristics, :through => :characteristic_points
      has_many :characteristic_points
accepts_nested_attributes_for :characteristic_points
attr_accessible :characteristic_points_attributes
end

class Characteristic < ActiveRecord::Base
  attr_accessible :name
  has_many :politicians, :through => :characteristic_points
  has_many :characteristic_points

end

class CharacteristicPoint < ActiveRecord::Base
  attr_accessible :characteristic_id, :politician_id, :score_obtained
  belongs_to :politicians
  belongs_to :characteristics
end

我需要做的是,从PoliticiansController(对于现有政治家)我需要保存模型中每个特征记录的分数。例如: 1)表中有一些特征(C1,C2,C3) 2)现在,当我选择score_update动作时,我需要提供一个循环遍历所有特征项的表单,并提供一个表单来添加分数 3)在更新时,必须使用步骤2中的指定值填充相同的表单,并允许用户使用新记录进行更新。 (目前它在视图上创建重复条目并在characteristic_points表上重新创建记录,我只是不需要这样做。)

以下是我现有的代码:

控制器

 def score_card
    @politician = Politician.find(params[:id])
    @characteristics = Characteristic.roots
    @politician.characteristic_points.build
  end
  def score_card_update
    @politician = Politician.find(params[:id])

    respond_to do |format|
      if @politician.update_attributes(params[:politician])
        format.html { redirect_to score_card_cms_politician_path(@politician), notice: 'Score card successfully updated.' }

      else
        format.html { render action: "edit" }

      end
    end
  end

视图

<%= form_for @politician,:url => score_card_update_politician_path,:html =>{:method => :post}  do |f| %>


                <% @characteristics.each do |characteristic| %>

                        <%= f.fields_for :characteristic_points do |builder|  %>
                        <%= render 'characteristic_point_fields', :f => builder, :politician => @politician, :characteristic => characteristic %>
                        <% end %>
                <% end %> 


    <%= f.submit "Update score"%>

<% end %>

_characteristic_point_fields.html.erb

<%= f.hidden_field :characteristic_id, :value => characteristic.id %>
<%=f.label characteristic.name%>
<%= f.text_field :score_obtained %>

希望这很清楚,任何帮助都非常感谢。

0 个答案:

没有答案