0

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'} do |f|
  = f.label :group
  = f.select :groups, @groups

そしてポストの部分params

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

今言っているのは"undefined method、"1":String"` に対して each' ということです。どうすればそれを取り除くことができますか?

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

まず、select ステートメントでは 1 つのグループしか選択できません。つまり、belongs_to 関係に似ています。「has_and_belongs_to_many」関係が必要で、必要な結合テーブルを作成したと仮定して、チェックボックスを使用してグループを選択できます。何かのようなもの

<% for group.find(:all) %>
   <div>
        <%= check_box_tag "user[group_ids][]", group.id, @user.groups.include?(カテゴリ) %>
        <%= グループ名 %>
   </div>
<%終了%>
于 2013-05-10T09:25:37.920 に答える