2

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

1 Answer 1

4

Change:

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

to

<%= f.fields_for(:tags, Tag.new) do |tag_form| %>
Sign up to request clarification or add additional context in comments.

2 Comments

that did it, thanks, @BroiSatse ! Do you mind directing me to some resource/documentation to explain why? Thanks again.
@ahimmelstoss - Best doc is always the source, no documentation will ever tell you the whole story behind the curtain. Here are two methods to look at: apidock.com/rails/ActionView/Helpers/FormBuilder/fields_for and apidock.com/rails/ActiveRecord/AttributeAssignment/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.