私はレールを初めて使用し、ユーザーが多くのチームに所属でき、チームに多くのユーザーが含まれるアプリを作成しようとしています。これが私のモデル クラスと移行ページです。さまざまなチームをクリックしてユーザーを割り当てることができるサインアップ ページを作成しようとしています。デフォルトなしのチームを持つことは、実装するのに適しています。
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :teams
accepts_nested_attributes_for :teams
end
class Team < ActiveRecord::Base
has_many :users
attr_accessible :name
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.references :teams
t.timestamps
end
end
end
class CreateTeams < ActiveRecord::Migration
def change
create_table :teams do |t|
t.string :name
t.references :users
t.timestamps
end
end
end
作成メソッドのコントローラーのコードは次のとおりです
def create
@users = User.all
@user = User.new(params[:user])
if @user.save
flash.keep[:success] = @user.name + " Added to list of Users!"
redirect_to users_path
else
render 'index'
end
end
ここに私のビューファイルのコードがあります
<% for team in @teams %>
<%= check_box_tag 'user[team]', team.name, @user.team_name.include?(team.name)%>
<%= team.name -%>
<% end %>
ただし、出力は「チーム」のみです。値が実際にオブジェクトに渡されているかどうかはわかりません。
編集:チェックボックスのドキュメントシートを読む必要がありました。問題の原因となったパラメーターは、初期化された値に対して true および false に変更された可能性があります。