1

我正在尝试从嵌套表单创建/更新一些 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 %>

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

4

0 回答 0