I have Addresses
, Lists
, and AddressListMemberships
.
In this particular application there are over a thousand List
s and many thousands of Addresse
s.
I've implemented a UI page to let users control a List
's Address
es. 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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.