Monday, 15 September 2014

Rails 4 has_and_belongs_to_many -



Rails 4 has_and_belongs_to_many -

i have 2 models. venues , categories. related each other has_and_belongs_to_many

categories pre populated , in form want display multi-select allow choosing categories venue while adding 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 |t| t.integer "category_id", null: true t.integer "venue_id", null: true end add_index :categories_venues, ["category_id", "venue_id"]

most of examples online show how create models another. not able figure out how have multi select alternative user can select 1 or more categories , save automatically.

do need utilize builder in controller? , add together accepts_nested_attributes_for ?

am new rails , been trying search , read through docs 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>

well problem wasn't creating relationships well. we've fixed little changes:

def category_ids params.permit(category_ids: []) end def venue_params #removed category_ids permit end def create @venue = venue.new(venue_params) if @venue.save category_ids.each {|id| @venue.categories << category.find(id)} # rest of code end

and update:

def update @venue = venue.find(params[:id]) if @venue.update(venue_params) @venue.categories.delete_all category_ids.each {|id| @venue.categories << category.find(id) }

ruby-on-rails ruby-on-rails-4 relationship has-and-belongs-to-many

No comments:

Post a Comment