我是Rails 3的新手,并且无法在Join表中保存记录。我一直在环顾四周,尝试通过本网站以及文档或书籍找到不同的示例,但我不明白为什么我无法使用它。我正在尝试通过创建角色并将它们关联到用户来创建授权。到目前为止,我一直试图从用户控制器中的更新操作中分配角色,但没有获胜。保存记录加入表Has_many:通过
我有3个型号:在User.rb,role.rb和assignment.rb(连接表)
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy
has_many :roles, :through => :assignments, :foreign_key => :role_id
accepts_nested_attributes_for :roles
attr_accessor :password, :role_ids
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :status, :description, :username, :roles_attributes
...
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments, :foreign_key => :user_id
accepts_nested_attributes_for :users
attr_accessible :name
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :roles
end
在更新操作的用户控制器我有以下
class UsersController < ApplicationController
...
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
@user.roles.build
flash[:success] = "Profile updated"
redirect_to @user
else
@title = "Edit" + " " + @user.username
render 'edit'
end
end
...
end
,并在“编辑”视图页面我打算复选框更新与相关联的角色的用户记录:
编辑:改变了“车ck_box“和”check_box_tag“...复选框正确显示,但值不会被保存。
<%= form_for(@user) do |f| %>
...
<div class="field">
<%= f.label :roles %><br />
<%= f.fields_for :role_ids do |r| %>
<% @roles.each do |role| %>
<%= check_box_tag "user[roles][]", role.id, @user.roles.include?(role.id) %>
<%= role.name %>
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
<% end %>
</div>
<% end %>
有了这段代码,我甚至会在'角色'没有关联的地方出错。
编辑:这是用accepts_nested_attributes_for :role
纠正。谢谢!
未找到名称“角色”的关联。它已被定义?
我真的很困惑,我做错了什么。您的帮助将不胜感激。
的Aurelien
谢谢@mosch,它修复了关联问题!不幸的是,我仍然遇到了将角色ID保存到分配表的问题。 –