Not work has_many :through association in rails 2.3.5
Models:
class Role < ActiveRecord::Base
attr_accessible :name
has_many :assignments
has_many :users, :through => :assignments
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :assignments
has_many :roles, :through => :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
In the view form of user
- for user in User.all
= check_box_tag 'role[user_ids][]', user.id, @role.users.include?
(user)
=h user.name
When I create a new user, nothing happens, the array of user_ids is
empty
I have a typical method in controller:
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = “Successfully created user.”
redirect_to @user
else
render :action => ‘new’
end
end
I thought it automatically saves the attribute :role_ids
I need to explicitly save it?
On 25 mayo, 10:23, Frederick C. [email protected]
On May 24, 11:08 pm, Alexander [email protected] wrote:
In the view form of user
- for user in User.all
= check_box_tag 'role[user_ids][]', user.id, @role.users.include?
(user)
=h user.name
When I create a new user, nothing happens, the array of user_ids is
empty
Those checkboxes will result in params[‘role[user_ids]’] being set to
an array of user ids - What does your controller code look like? If
it’s just a classic User.create params[:user] that clearly isn’t being
used at all
Fred
On May 25, 12:35 pm, Alexander [email protected] wrote:
end
I thought it automatically saves the attribute :role_ids
But that’s not what your form (at least not in your initial post) is
doing - it’s setting the attribute :user_ids in params[:role] which
you aren’t using. Did you actually mean to create a checkbox
user[role_ids][] for each role ?
Fred
On May 25, 2:45 pm, Alexander [email protected] wrote:
you are right, my mistake
in the user form i have this
- for role in Role.all
= check_box_tag "user[role_ids][]", role.id, @user.roles.include?
(role)
=h role.name
If you look at your development log file does it actually look like
those parameters are being submitted as you expected ?
Fred
you are right, my mistake
in the user form i have this
- for role in Role.all
= check_box_tag "user[role_ids][]", role.id, @user.roles.include?
(role)
=h role.name
On 25 mayo, 13:56, Frederick C. [email protected]
i found the solution, it was so simple as add this to model of user
attr_accessible :role_ids
anyway thanks for all your answers