I have a simple blog app, where I want to be able to create a Post and also create a new Tag for it in the same form, using a nested form.

Post and Tag have a many-to-many relationship, via a join table:

class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag
end

Here's the tag model:

class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, :through => :post_tags

  validates_presence_of :name
  validates_uniqueness_of :name
end

Post model accepts nested attributes for tags:

class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => :post_tags
  accepts_nested_attributes_for :tags
  validates_presence_of :name, :content
end

On the posts controller, I permit tags_attributes:

    def post_params
      params.require(:post).permit(:name, :content, :tag_ids => [], :tags_attributes => [:id, :name])
    end

In my form for a new post, where I want to be able to either associate already existing tags (via checkboxes) or create a new one via a nested form using fields_for:

....
  <div class="field">
   <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %><br>
    <%= f.fields_for [@post, Tag.new] do |tag_form| %>
    <p>Add a new tag:</p><br>
     <%= tag_form.label :name %>
     <%= tag_form.text_field :name %>
    <% end %>
  </div>

 <div class="actions">
  <%= f.submit %>
 </div>

 <% end %>

My error is "Unpermitted parameters: tag":

Parameters: {"utf8"=>"✓",  "authenticity_token"=>"dZnCgFxrvuoY4bIUMMxI7kTLEr/R32pUX55wwHZsS4Q=", "post"=>{"name"=>"post title", "content"=>"post content", "tag_ids"=>[""], "tag"=>{"name"=>"new tag"}}, "commit"=>"Create Post"}
Unpermitted parameters: tag
有帮助吗?

解决方案

Change:

<%= f.fields_for [@post, Tag.new] do |tag_form| %>

to

<%= f.fields_for(:tags, Tag.new) do |tag_form| %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top