Rails correct way to submit nested parameters in form

时间:2015-07-31 20:49:28

标签: ruby-on-rails

This code successfully creates a new Notice, as intended:

In the submit form:

<%= form_tag( {controller: "notices", action: "create"}, method: "post", class: "comment_form", html: { multipart: true } ) do %>
  .
  <%= hidden_field_tag "notice[supernotice][commentee_id]", notice.id %>
  .
<% end %> 

In the notices_controller.rb:

def create
  @character = Character.find_by(callsign: params[:callsign])
  @notice = @character.notices.build(notice_params)
  if @notice.save
    if !params[:notice][:supernotice][:commentee_id].nil?
      @notice.create_comment(params[:notice][:supernotice][:commentee_id]) # hits the create_comment method in notice.rb
    end
  end

def notice_params
  params.require(:notice).permit(:content, :picture, :latitude, :longitude, supernotice_attributes: [:commentee_id] )
end

Class notice.rb:

has_one :supernotice, through: :active_comment_relationship, source: :commentee
accepts_nested_attributes_for :supernotice

def create_comment(other_notice_id)
  create_active_comment_relationship(commentee_id: other_notice_id)
end

However, the logs show the error: Unpermitted parameter: supernotice. How do I get rid of this error? What is wrong with the way I am submitting the nested parameter?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

<%= hidden_field_tag "notice[supernotice_attributes][0][commentee_id]", notice.id %>

但一般来说,创建嵌套属性的方式是错误的。您应该从form_for帮助程序开始,然后对于嵌套属性使用f.fields_for帮助程序。例如:

<%= form_for @notice do |f| %>

  <%= f.fields_for :supernotice do |ff| %>
    <%= ff.hidden_field :commentee_id, @notice.id %>
  <% end %>

<% end %>

还有一件事。如果你按照我提出的方式创建表单,很可能你根本不需要那个隐藏字段,因为rails会处理它。意思是,在创建rails期间,将知道在commentee_id上​​填充的id。