Association IDs with Ease

Holy crap, that is a corny title. Oh, but it does have a point! I found this out the other day, and who knows how long it’s been in Rails ( didn’t check the old docs ) , but you can actually assign collection ids to an associated object! Ok that’s confusing, just here’s the example already:

I was working on a trip booking site in Rails, and I needed the ability to assign optional “excursions” to “passengers”. So of course UI-wise, I’m using checkboxes… but backend-wise I’m thinking ‘crap, I don’t want to loop through each of the selected ones and assign them one at a time’. Literally, that’s what I was thinking. So I did some snooping of the Rails docs in the Association::ClassMethods area… and found the following VERY useful info. :)

My example, uses the checkboxes, so in my view I have the following (note the empty string as the last param on the check_box, so that the default/unchecked value is NOT 0 (zero) .. that is unless you want to do more logic in your controller to check for 0 values to throw out).. anyway, the code:


<% @trip.excursions.each do |excursion| %>
  <%= check_box :trip_excursion, :excursion_id, { :id => "excursion_#{excursion.id}", :name => 'excursions[]' }, excursion.id, "" %>
  <%= label 'trip_excursion', 'excursion_id', "#{excursion.name} #{excursion.days_offered}", :for => "excursion_#{excursion.id}" %>
<% end %>

Then in my passengers controller (both create and update methods), I simply have:


@passenger = @trip.passengers.create params[:passenger]
@passenger.excursion_ids = params[:excursions]

One of my favorite things is, you can say collection_ids = *anything .. it can be null, an empty array, an empty string, a not-empty array, a single integer, and so on and so forth. This was actually very useful for doing the update (moreso than the create), since doing the update would have otherwise required checking for already selected excursions and comparing the values of the params, deleting those that were no longer “checked”. This takes care of that by just setting the IDs explicitly, which will automatically remove the associations that are no longer in the new value-set. :) Happy coding…

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in Development, Ruby on Rails. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>