0
我是新來的rails,我試圖創建一個應用程序,用戶可以屬於許多團隊,團隊包含許多用戶。這裏是我的模型類和遷移頁面。我正在嘗試創建一個註冊頁面,您可以點擊不同的團隊來分配用戶。有一個默認的沒有團隊會很好實施。has_many關係的複選框
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的initlized值。
謝謝!這有很大幫助。我用的是@ user.teams.include?(team.name) – ChairmanMeow
但是我得到了一個新的錯誤,叫做'Can not mass-assign protected attributes:team'你知道這是爲什麼嗎? – ChairmanMeow
你在'Team'模型中嘗試過使用'accep_nested_attributes_for'嗎?嘗試在你的'Team'模型中聲明'accep_nested_attributes_for:users'。有關詳細信息,請參閱http://guides.rubyonrails.org/security.html#mass-assignment。 – richsinn