我在第二個代碼塊(如果您不想要所有細節)中隔離了問題:我可以創建新用戶來自賬戶模型。我無法從帳戶模型中分配這些用戶角色。我正在使用fields_for,當我嘗試將role_ids分配給角色模型時,此方法不起作用。我的數據庫是建立在以下方式:複雜形式 - 以單一形式管理多個模型 - (3級瘋狂)
Account模型的has_many:用戶
用戶模型has_and_belongs_to_many:角色, belongs_to的:佔
角色模型has_and_belongs_to_many:users
的意見/帳號/ new.html.erb
<% for user in @account.users %>
<% fields_for "account[user_attributes][]", user do |account_fields| %>
<p>Login : <%= account_fields.text_field :login %>
<p>Email : <%= account_fields.text_field :email %>
<p>Password : <%= account_fields.password_field :password %>
<p>Confirm Password : <%= account_fields.password_field :password_confirmation %>
<%= account_fields.hidden_field :account_id, :value => :id %>
<% end %>
<% end %>
<% for role in @account.users.first.roles %>
<% fields_for "account[role_attributes]]", role do |role_fields| %>
<%= role_fields.hidden_field :role_ids, :value => '[1]' %>
<% end %>
<% end%>
在account.rb模型相關聯的setter方法:使用堆棧跟蹤我已經分離出的問題「未定義的方法'角色的#」在線路34上,下面標明:
def user_attributes=(user_attributes)
user_attributes.each do |attributes|
users.build(attributes)
end
end
def role_attributes=(role_attributes)
role_attributes.each do |attributes|
users.roles.build(attributes) #error here (stacktrace)
end
end
最後,賬戶控制器內我建立用戶和角色存儲:
def new
@account = Account.new
1.times { @account.users.build }
1.times { @account.users.first.roles.build }
從康索爾的@ accounts.users.first.roles.build證明:
>> account
=> #<Account id: 1, subdomain: "justinzollars", created_at: "2010-02-08 14:41:13", updated_at: "2010-02-08 14:41:13">
>> account.users
=> [#<User id: 13, login: "jayz", email: "[email protected]", crypted_password: "f9a3d618fc650d285a90f9775508c13784891b97", salt: "f497a7dd909b695caff1f6310e710245615d55b6", created_at: "2010-02-08 20:25:48", updated_at: "2010-02-08 20:25:48", remember_token: nil, remember_token_expires_at: nil, account_id: 1>, #<User id: 16, login: "jasonwade23", email: "[email protected]", crypted_password: "06581b47cfac7a529773d61dc0b1d5d6c0da6c08", salt: "93f8b99cd9da60b904d553fcc7843bfb66352c3e", created_at: "2010-02-13 07:46:14", updated_at: "2010-02-13 07:46:14", remember_token: nil, remember_token_expires_at: nil, account_id: 1>]
>> account.users.first
=> #<User id: 13, login: "jayz", email: "[email protected]", crypted_password: "f9a3d618fc650d285a90f9775508c13784891b97", salt: "f497a7dd909b695caff1f6310e710245615d55b6", created_at: "2010-02-08 20:25:48", updated_at: "2010-02-08 20:25:48", remember_token: nil, remember_token_expires_at: nil, account_id: 1>
>> account.users.first.roles
=> [#<Role id: 1, name: "admin">, #<Role id: 2, name: "alt">]
>>
我可以設置新角色,我需要能夠分配當前角色。 SQL等效項: SQL(0.1ms)INSERT INTO「roles_users」(「role_id」,「user_id」)VALUES(6,29) 是否有關於創建新模型的規定? – 2010-02-14 00:08:57
其中coure的role_id將被修復,並且user_id將是當前新的user_id – 2010-02-14 00:49:48
我在我的回答中添加了一些解釋。希望你會發現它有用! – klew 2010-02-14 13:11:26