0

我需要使用 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”:String“`的每个'。我该如何摆脱它?

4

2 回答 2

1

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

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

但是我个人更喜欢在使用模型时使用“collection_select”:

#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 })
于 2013-05-10T10:08:06.177 回答
0

首先,选择语句只允许您选择一个组。所以,这更像是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) %>
        <%= 组名 %>
   </div>
<% 结束 %>
于 2013-05-10T09:25:37.920 回答