I have two models. Venues and Categories. They are related to each other as has_and_belongs_to_many
Categories are pre populated and in the form i want to display a multi-select to allow choosing the categories for a venue while adding a venue.
venue.rb
class Venue < ActiveRecord::Base
has_and_belongs_to_many :categories
end
category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :venues
end
Join Table
create_table "categories_venues", id: false, force: true do |t|
t.integer "category_id", null: true
t.integer "venue_id", null: true
end
add_index :categories_venues, ["category_id", "venue_id"]
Most of the examples online show how to create the models from with another. I am not able to figure out how to have a multi select option where the user can select one or more categories and save it automatically.
Do i need to use builder
in the controller? and add accepts_nested_attributes_for
?
Am new to Rails and been trying to search and read through the docs as well.
Controller
def new
@venue = Venue.new
@categories = Category.all.order('name ASC')
@countries = Country.all.order('name ASC').limit(25)
@regions = Region.all.order('name ASC').limit(25)
@cities = City.all.order('name ASC').limit(25)
#render plain: @categories.inspect
end
View
<div class="form-group">
<%= f.label :parent_id, "Categories:<span class='mandatory'>*</span>".html_safe,:class => 'col-sm-2 control-label' %>
<div class="col-sm-3">
<%= f.collection_select(:category_ids, @categories, :id, :name, { :prompt => true }, { :class => 'select-search', :selected => params[:user_id], :data => { :placeholder => 'Please Choose' } }) %>
<%= show_errors(@venue, :category_ids).html_safe %>
</div>
</div>