Has_many :through with checkboxes?

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
checkboxes?

=begin code

Here’s what my models look like:

user.rb

has_many :subscriptions
has_many :cats, :through => :subscriptions

cat.rb

has_many :subscriptions
has_many :users, :through => :subscriptions

subscription.rb

belongs_to :user
belongs_to :cat

In the view, I can display a user’s subscriptions as a set of

checkboxes just fine:

cats.rhtml

<% cats.each do |cat| %>
<%= check_box_tag(“cats[]”, cat.id, @user.cats.include?(cat)) %

cat.name
<% 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! :slight_smile:

account_controller.rb

@user = User.find(params[:id])

subscriptions = Subscription.find(:all, :conditions => “user_id =
@user”)
subscriptions.each do |subscription|
subscription.destroy
end

categories = params[:cats]
categories.each {|cat|
subscription = Subscription.new(:cat_id=>cat, :user_id=>@user)
subscription.save
}

=end code

Does anyone know what’s going wrong here?

Very grateful for your help,

Jacob

Jacob P.

I think I maybe sorted out the update script. Here’s what I have now:

= begin

user.rb

has_many :subscriptions, :dependent => true
has_many :cats, :through => :subscriptions

cat.rb

has_many :subscriptions, :dependent => true
has_many :users, :through => :subscriptions

subscription.rb

belongs_to :user
belongs_to :cat

account_controller.rb#cats

def cats
@user = User.find(params[:id])
@cats = Cat.find(:all)
if request.post?
# clear user subscriptions
@user.subscriptions.clear
# if cats param is set (not nil), create the subscriptions
if params[:cats]
categories = params[:cats]
categories.each {|cat|
sub = Subscription.create(:user_id => @user, :cat_id => cat)
sub.save
}
end
flash[:notice] = “Category subscriptions updated.”
redirect_to :action => :cats, :id => @user
end

=end

That all seems to work! I hope this helps someone!

Best,

Jacob

Jacob P.

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