I have a User model and a Role model. They are joined by a has_and_belongs_to_many relationship. When an admin creates a user I want them to be able to assign a role to the user and have it saved when I call @user.save
The thing is though is that I get a warning that I can't mass-assign the roles relationship.
Any suggestions on how to go about this, I am on Rails 2.3.2
Thanks.
Edit: Code as requested.
user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles,
:join_table => "users_roles",
:foreign_key => "role_id",
:associated_foreign_key => "user_id"
end
role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users,
:join_table => "users_roles",
:foreign_key => "user_id",
:association_foreign_key => "role_id"
end
View: new.html.haml
- form_for(@user, users_path(:subdomain => current_account.subdomain)) do |f|
.input_set
= f.label(:login, "Username")
= f.text_field(:login)
.input_set
= f.label(:name)
= f.text_field(:name)
.input_set
= f.label(:email)
= f.text_field(:email)
- fields_for("user[roles][]", Role)do |user_role|
.input_set
%label Role
= user_role.select(:name, Role.all.map{|r| [r.name, r.id] })
.input_set
= f.label(:password)
= f.password_field(:password)
.input_set
= f.label(:password_confirmation, "Password Again")
= f.password_field(:password_confirmation)
.input_set
%label
= f.submit "Add User"
And I want the Role to be saved to the user by calling @user.save in my create option. Is that possible? Or is this a relationship I can't use that way, would it need to a has_many relationship for me to be able to do this.