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 method
each' "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
Post a Comment