我是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保存到分配表的問題。 –