在视图中分配has_and_belongs_to_many字段的值

时间:2013-05-10 09:16:48

标签: ruby-on-rails ruby

我需要使用html标记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'} do |f|
  = f.label :group
  = f.select :groups, @groups

以及帖子params

的部分内容
{ ....
  "groups"=>"1"
  ...
}

它现在所说的是"undefined method每个'为“1”:字符串“`。我如何摆脱它?

2 个答案:

答案 0 :(得分:1)

你应该在数组中有组,并添加多个选项(如果用户应该有多个组),如下所示:

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

但我个人更喜欢使用&#39; collection_select&#39;使用模型时:

#controller
def new
  @user = User.new
  @groups = Group.all
end

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

答案 1 :(得分:0)

首先,select语句只允许您选择一个组。所以,那更像是belongs_to的关系。让我们假设你想要一个“has_and_belongs_to_many”关系,并且你已经创建了所需的连接表,你可以使用一个复选框来选择组。像

这样的东西
<% for group in Group.find(:all) %>
   <div>
        <%= check_box_tag "user[group_ids][]", group.id, @user.groups.include?(category) %>
        <%= group.name %>
   </div>
<% end %>
相关问题