我在下面的第二个代码块中隔离了问题(如果您不想要所有详细信息):我可以从帐户模型创建新用户。我无法从帐户模型中分配这些用户角色。我正在使用 fields_for,当我尝试将 role_ids 分配给角色模型时,此方法不起作用。我的数据库是按以下方式设置的:
账户模型 has_many : users
用户模型 has_and_belongs_to_many :角色,belongs_to :帐户
角色模型 has_and_belongs_to_many :用户
意见/帐户/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 行的“未定义方法 `roles' for #”,标记如下:
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 }
来自 consol 的 @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: "jz@jz.com", 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: "jasonwade@gmail.com", 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: "jz@jz.com", 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">]
>>