0

Currently I have a Category and Post model, joined by a HABTM relationship.

Posts belong to multiple categories and have many attributes.

Categories just have a Name Property.

How do I create a multi-select form in my Posts _form.html.erb so I can select which categories I want the post to be assigned to?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jonathan
  • 673
  • 1
  • 10
  • 32
  • Welcome to Stack Overflow. Please use bold and italics sparingly, if at all, in your question's text. Like typing in all caps, they're like yelling, and really only distract instead of help. Think of SO like it's an encyclopedia of programming problems Q&A, only mixed with a Wikipedia editing style. Write it like you'd see in a reference book, concise, clear, and not overly decorated. It's ok to be friendly but it isn't a conversation. Also, we don't use salutations ("Hi"), valedictions ("Thanks") or signatures ("Jonathan") in the questions or answers. – the Tin Man Mar 27 '15 at 17:42

2 Answers2

1
<%= form_for @post do |f| %>
  <div>
    <%= f.label :category_ids, "Categories" %><br />
    <%= f.collection_select :category_ids, Category.order(:name), :id, :name, {}, {multiple: true} %>
  </div>

  <div>
    <%= f.submit 'Submit' %>
  </div>
<% end %>
archit gupta
  • 954
  • 10
  • 13
0

Try using select and collection. You may have to change the collection, not sure exactly what Category options you want to be able to choose from. Something like this:

<%= f.input :post, as: :select, collection: Category.posts, include_blank:false %>

Or checkout out the collection_select form helper method http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

Ryan Rebo
  • 1,278
  • 2
  • 13
  • 27