I’am new to ROR and I have a problem.
I have to models “rights” and “roles” on a has_and_belongs_to_many
relationship, through “roles_rights” table. When I try to add a new role
although I put in my form fields for each right, a record is added to
table roles but none to roles_rights.
I am using Ruby 1.8.4 rails 1.0 mysql 5.0
here is my code:
controller:
def create @role = Role.new(params[:role]) @role.rights = Right.find(@params[:right_ids])if @params[:right_ids]
if @role.save
flash[:notice] = ‘Role was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
view:
Name
<%= text_field 'role', 'name' %>
Rights
<% for right in @rights %>
<%= right.name %>
<% end %>
</ul>
==================================
model:
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
has_and_belongs_to_many :rights, :join_table => ‘roles_rights’
end
class Right < ActiveRecord::Base
has_and_belongs_to_many :roles, :join_table => ‘roles_rights’
end
the way collections work is that 1) they are saved immediately if the
parent
record is not a new record or 2) are saved when the parent record is
saved.
your situation clearly falls under #2. so they should be save when you
save
the @role record. since this isn’t happening, it’s possible that there
are
no rights in the collection.
then load the app and create a new role. in the breakpointer, you can
then
examine the vars to make sure they have the values you expect them to
have.
CTRL-D to end the breakpoint session.
I’am new to ROR and I have a problem.
I have to models “rights” and “roles” on a has_and_belongs_to_many
relationship, through “roles_rights” table. When I try to add a new role
although I put in my form fields for each right, a record is added to
table roles but none to roles_rights.