1

*Note to view all code, follow the link

I am creating new "accounts". Each new Account have_many :users. Users have_and_belong_to_many roles. I am trying to assign EXISTING roles to new users, in the new account form. Typically an easy process however...

The have_and_belong_to_many association between Users and Roles implies that users and roles are associated by a join table. I don't have a model to work with. So I am not sure how to go about coding this. I'm able to create new Roles, using methods outlined here (in the answer) but I am clueless as to assign existing Roles to new users through the account model.

The SQl equivalent would be something like this: SQL (0.1ms) INSERT INTO "roles_users" ("role_id", "user_id") VALUES (6, 29)Where I need 29 to function like the ID of the new user created in rails i.e. VAULES (6, ID)

Current Code: (creates a new role)

<% f.fields_for :users do |builder| %>
<%= render 'user_fields', :f => builder %>
<p>Login  : <%= f.text_field :login %>
<p>Email  : <%= f.text_field :email %>
<p>Password  : <%= f.password_field :password %>
<p>Confirm Password  : <%= f.password_field :password_confirmation %>
<%= f.hidden_field :account_id, :value => :id %>


<% f.fields_for :roles do |builder| %>
     <%= builder.hidden_field :name, :value => 'test' %>
<% end %>

Account.rb

has_many :users
accepts_nested_attributes_for :users

User.rb

has_and_belongs_to_many :roles
accepts_nested_attributes_for :roles

accounts_controller.rb

def new
    @account = Account.new
    #builds user and roles in memory
    1.times do
      user =  @account.users.build 
    1.times { user.roles.build }
  end
4

1 回答 1

1

问题是您在不应该使用的情况下使用了accepts_nested_fields。它用于从调用模型创建和销毁引用模型的项目。您想从用户模型而不是角色本身来管理关联。

以下是必须要做的事情:

  1. 从 user.rb中删除accepts_nested_attributes_for :roles(可选,但推荐)
  2. 分配给用户创建表单中的 role_ids 字段。

这种观点应该说明这一点:

<% f.fields_for :users do |builder| %>
<p>Login  : <%= f.text_field :login %>
<p>Email  : <%= f.text_field :email %>
<p>Password  : <%= f.password_field :password %>
<p>Confirm Password  : <%= f.password_field :password_confirmation %>
<%= f.hidden_field :account_id, :value => :id %>

<%= f.collection_select :role_ids, Role.all, :id, :name, {}, :multiple => true %>

<% end %>

在不更改任何其他内容的情况下,Rails 将在创建时填充连接模型,而不是修改现有角色或创建新角色。

于 2010-02-14T02:05:33.700 回答