views:

42

answers:

1

I have Addresses, Lists, and AddressListMemberships.

In this particular application there are over a thousand Lists and many thousands of Addresses.

I've implemented a UI page to let users control a List's Addresses. I've added these actions...

class ListsController < ApplicationController

  # ...

  def add_address
    @list = List.find(params[:id])
    address = Address.find(params[:address_id])
    @list.addresses << address unless @list.addresses.include? address
    redirect_to(manage_list_addresses_path(@list))
  end

  def remove_address
    @list = List.find(params[:id])
    address = Address.find(params[:address_id])
    @list.addresses.delete address
    redirect_to(manage_list_addresses_path(@list))
  end

end

Everything works beautifully.

However, those actions look like they have too much code in them. I'm guessing there's a more succinct, Railsish way to implement them, particularly this thing...

@list.addresses << address unless @list.addresses.include? address
+2  A: 

No it isn't. The object that your address list membership is attached has a method on it you can use. So on your Address model you could access:

@address.list_ids

This is an array of ids for the join. So if you have:

@address.list_ids = [1,2,3]

there will be three joined records. If you want to get rid of List with id 2 you would make it

@address.list_ids = [1,3]

Checkboxes are a great interface to this, you should check out this railscast, the HMT relationship and HABTM relationship provide the _ids array methods out of the box in ActiveRecord.

That's the best way to do it.

railsninja
You're envisioning a different situation from what I'm dealing with. Yes, checkboxes are a great solution in many cases. I'll try to make my question clearer.
Ethan