ruby on rails - Assign the values of has_and_belongs_to_many field at a view -


i need assign groups user @ view using html tag select.

#model class user < activerecord::base   has_and_belongs_to_many :groups   attr_accessible :groups, #...... end  class group < activerecord::base   has_and_belongs_to_many :users end   #controller   def new     @user = user.new     @groups = group.all.map{|x| [x.name, x.id]}   end    def create     @user = user.new params[:user]     # @user.groups     if @user.save       flash[:success] = 'ok'     else       render action: 'new'     end   end  #view = form_for @user, url: {action: 'create'} |f|   = f.label :group   = f.select :groups, @groups 

and part of post params

{ ....   "groups"=>"1"   ... } 

what says "undefined methodeach' "1":string"`. how rid of it?

you should have groups in array, , add multiple option (if user should have more 1 group) this:

#view = form_for @user, url: {action: 'create'} |f|   = f.label :group   = f.select :groups, [@groups], {}, { :multiple => true } 

however prefer use 'collection_select' when working models:

#controller def new   @user = user.new   @groups = group.all end  #view = form_for @user, url: {action: 'create'} |f|   = f.label :group   = f.collection_select(:group_ids, @groups, :id, :name, {}, { :multiple => true }) 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -