Topic: HATBM question...

I'm trying to help a friend with a HABTM question.  I've only used HMT so I'm not too upto speed on some of the proper plumbing of HATBM and I would appreciate any advice you can offer.

The current situation, he has a "Question" model class and a "Keyword" model class and we are working on with a keywords_questions join table.  Both model classes have the habtm relationship defined.

He's trying to setup the new question creation view and we're trying to figure out the correct stuff to put into the select to properly plumb the system.

He's been trying variations on

collection_select "question", "keyword_ids", @keywords

but there's no "keyword_ids" function defined on the question class.  I know in the HMT join models I'm used to you can't streamline the process and you have to loop over the list of things to add (as HMT assumes you have extra attributes on the join, this makes sense).  However I would have thought that HABTM would have had some magic to help in this common case.  Am I missing something?

I supposed I can help my friend code up keyword_ids= and keyword_ids methods...

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.

Re: HATBM question...

The keyword_ids= method is generated automatically. See this documentation for creating a HABTM relationship. It uses checkboxes, but it shouldn't be too hard to apply it to a multiple select box.

http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM

Railscasts - Free Ruby on Rails Screencasts

Re: HATBM question...

Interesting, so <other>_ids= (mutator) is defined automatically, but not <other>_ids  (reader)....  I know he's got it working with a solution based on the link you gave, but I know I'll definitely want to play around with it sometime to find a more elegant solution.  I wonder if I define the reader manually if I can get some of the existing tools to behave better. 

Thanks

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.

Re: HATBM question...

Here's some code if you want:

View:

<select name="question[keyword_ids][]" id="question_keyword_ids" size="5" multiple="multiple">
  <%= options_from_collection_for_select Keyword.find(:all), :id, :name, @question.keywords.collect(&:id) %>
</select>

In the controller you can create/update the question just like normal (passing the params[:question] hash), but there is one gotcha. If no keyword is selected, the params[:question][:keyword_ids] will not be set to an empty array. To fix this problem, you can add this line to the controller before updating the attributes:

params[:question][:keyword_ids] ||= []

Hope that helps.

Last edited by ryanb (2006-08-17 17:11:49)

Railscasts - Free Ruby on Rails Screencasts