Just when I started getting the hang of has_and_belongs_to_many
relationships, I realize that I should probably convert several of my
app’s joins to has_many :through type relationships.
One example, pairing users with categories via subscriptions, where
each user can be the “owner” of a category, has given me particular
trouble when I try to update a user’s category subscriptions.
Has anyone figured out how to manipulate HMT relationship with
Here’s what my models look like:
has_many :cats, :through => :subscriptions
has_many :users, :through => :subscriptions
In the view, I can display a user’s subscriptions as a set of
checkboxes just fine:
<% cats.each do |cat| %>
<%= check_box_tag(“cats”, cat.id, @user.cats.include?(cat)) %
<% end %>
It’s the controller method’s that foul me up
I believe I should clear out a user’s subscriptions on submit
(to account for unchecked boxes and to start from scratch for the
next step) and then
I should add a subscription for each checked box
this doesn’t work, but it’s what I’m hacking on now–HELP!
@user = User.find(params[:id])
subscriptions = Subscription.find(:all, :conditions => “user_id =
subscriptions.each do |subscription|
categories = params[:cats]
subscription = Subscription.new(:cat_id=>cat, :user_id=>@user)
Does anyone know what’s going wrong here?
Very grateful for your help,