HABTM updating/saving behaviour

Newbie question (I guess).

I have a User whom can have some Preference. So the scracth model is:

class User < ActiveRecord:Base
[…]
has_and_belongs_to_many :preferences
[…]
end

class Preference < ActiveRecord:Base
[…]
has_and_belongs_to_many : users
[…]
end

In the migration I have created a table preferences_users with primary
keys
preference_id and user_id

In the view the choice of which preferences are connected to and user is
performed by means of a checkbox sets.

In my user_controller scalffold generated actions “create” and “update”
I
added the following lines:

[…]
params[:preferences].each { |k,v|
if v == 1 then #if checkbox is checked
preferences << Preference.find(k)
end
}
[…]
the user is saved or updated

So I have two question:

  1. Is there a better way to perform that check, ot any helper that
    already
    do that task?
  2. Actually in the join table preferences_users nothing is saved. I have
    to
    force the saving ?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs