rails 4更新嵌套属性确实有效

时间:2016-12-21 15:30:48

标签: ruby-on-rails-4 has-many

我尝试了关于这个问题的所有答案,但我仍然无法解决我的问题。 我需要控制器(和模型):清单和字段。

class NcchecklistsController < ApplicationController
def update
    if @ncchecklist.update(ncchecklist_params)
      redirect_to ncchecklists_url, notice: 'Check-list sauvgardée.'
    else
      render :index
    end
  end
private
    # Use callbacks to share common setup or constraints between actions.
    def set_ncchecklist
      @ncchecklist = Ncchecklist.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def ncchecklist_params
      params.require(:ncchecklist).permit(:name, ncfield_params: [:value, :id])
    end

字段控制器

class NcfieldsController < ApplicationController
private
    # Use callbacks to share common setup or constraints between actions.
    def set_ncfield
      @ncfield = Ncfield.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def ncfield_params
      params.require(:ncfield).permit(:name, :value, :ncchecklist_id)
    end

清单模型

class Ncchecklist < ActiveRecord::Base
  has_many :ncfields, dependent: :destroy
  attr_accessible :ncfields
  accepts_nested_attributes_for :ncfields
end

田野模型

class Ncfield < ActiveRecord::Base
  belongs_to :ncchecklist

end

观点:

<h1> Vos check-list </h1>
<% @ncchecklists.each do |ncchecklist| %>
  <%= form_for(ncchecklist) do |ncchecklist_form| %>
    <h3><%= ncchecklist.name %></h3>
    <% ncchecklist.ncfields.each do |field| %>
      <%= ncchecklist_form.fields_for :ncfields, field do |ncfield_form| %>
        <p>
          <%= ncfield_form.label :name, 'Tâche : ' %>
          <%= field.name %> : 
          <%= ncfield_form.label 'value_false', 'Non' %>
          <%= ncfield_form.radio_button :value, false %>
          <%= ncfield_form.label 'value_true', 'Oui' %>
      <%= ncfield_form.radio_button :value, true %>
        </p>
      <% end %>
    <% end %>
    <%= ncchecklist_form.submit 'Sauvegarder '+ncchecklist.name %>
  <% end %>
<% end %>

视图如下: view screen-shot

问题是当我改变单选按钮的值并且我点击保存时,没有任何反应。 我在日志中找到了这个:

Started PATCH "/redmine/ncchecklists/2" for ::1 at 2016-12-21 15:58:48 +0100
Processing by NcchecklistsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ncchecklist"=>{"ncfields_attributes"=>{"0"=>{"value"=>"false", "id"=>"2"}, "1"=>{"value"=>"false", "id"=>"3"}}}, "commit"=>"Sauvegarder Chef de projet", "id"=>"2"}
  Current user: anonymous
Redirected to http://localhost/redmine/ncchecklists

感谢帮助

1 个答案:

答案 0 :(得分:0)

控制器的强大参数只是有点偏差。 它们应该是$ {model} _attributes而不是$ {model} _params

def ncchecklist_params
  params.require(:ncchecklist).permit(:name, ncfields_attributes: [:value, :id])
end

您可以在问题结束时看到它在原始日志中发送,但强大的参数正在过滤掉它。