title: Rails using checkbox for adding tags to posts ( many to many )
body: <p>I have a Post model and Tag model with many to many relationships. </p>
  
  <h1>Post Model:</h1>
  
  <pre><code>class Post &lt; ActiveRecord::Base
      has_and_belongs_to_many :tags
  end
  </code></pre>
  
  <h1>Tag model:</h1>
  
  <pre><code>class Tag &lt; ActiveRecord::Base
      has_and_belongs_to_many :posts
  end
  </code></pre>
  
  <p>I also have a join table for <code>posts_tags</code> :</p>
  
  <pre><code>class JoinPostsAndTags &lt; ActiveRecord::Migration
    def change
      create_table :posts_tags do |t|
          t.integer :tag_id
          t.integer :post_id
  
          t.timestamps null: false
      end
    end
  end
  </code></pre>
  
  <p>Now, I need to provide multiple selection for selecting tags for a post.</p>
  
  <p><strong>Below is the post <code>form.html.erb</code></strong> </p>
  
  <pre><code>&lt;%= form_for @post do |f| %&gt;
    &lt;% if @post.errors.any? %&gt;
      &lt;div id="error_explanation"&gt;
        &lt;h2&gt;&lt;%= pluralize(@post.errors.count, "error") %&gt; prohibited this post     from being saved:&lt;/h2&gt;
  
        &lt;ul&gt;
        &lt;% @post.errors.full_messages.each do |message| %&gt;
          &lt;li&gt;&lt;%= message %&gt;&lt;/li&gt;
        &lt;% end %&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
    &lt;% end %&gt;
  
    &lt;div class="field"&gt;
  &lt;%= f.label :Name %&gt;&lt;br&gt;
  &lt;%= f.text_field :Name %&gt;
    &lt;/div&gt;
  
    &lt;div class="field"&gt;
      &lt;%= f.label :Email %&gt;&lt;br&gt;
      &lt;%= f.text_field :Email %&gt;
    &lt;/div&gt;
  
    &lt;div class="field"&gt;
      &lt;%= f.label :Message %&gt;&lt;br&gt;
      &lt;%= f.text_area :Message %&gt;
    &lt;/div&gt;
  
    &lt;% @tags= Tag.all %&gt;
    &lt;% if @tags %&gt;
    &lt;% @tags.each do |tag| %&gt;
      &lt;div&gt;
          &lt;%= check_box_tag "post[tag_ids][]", tag.id, @post.tags.include?(tag) %&gt;
          &lt;%= tag.name %&gt;
      &lt;/div&gt;
    &lt;% end %&gt;
    &lt;% end %&gt;
  
  
    &lt;br&gt;&lt;br&gt;
  
    &lt;%= link_to 'Create Tag', tags_path %&gt;
       &lt;br&gt;&lt;br&gt;
  
  
    &lt;div class="actions"&gt;
      &lt;%= f.submit %&gt;
    &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>It is not adding the selected tags to the post. I need to add the selected tags to the post. How can I do it.<br>
                                                                                                            But, in <strong>rails console</strong> if I use <code>post= Post.first</code> <code>tag= Tag.first</code>  <code>post.tags&lt;&lt;tag</code> it adds the <code>tag</code> to the <code>post</code>.<br>
  I don't have any special code in <code>post controller</code> to handle this. Please help me.</p>