# HABTM Associations In View

**URL:** <https://www.ruby-forum.com/t/habtm-associations-in-view/185353>\
**Category:** Rails\
**Created:** [March 18, 2010, 4:23pm UTC](https://www.ruby-forum.com/t/habtm-associations-in-view/185353 "2010-03-18T16:23:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![andy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/aeb1de/32.png) [@andy](https://www.ruby-forum.com/u/andy)\
**Post date:** [March 18, 2010, 4:23pm UTC](https://www.ruby-forum.com/t/habtm-associations-in-view/185353/1 "2010-03-18T16:23:46Z")

</div>

Hello,  
I wish I had the time to figure this out but I’m on a limited timeline  
to convince people to look at RoR instead of Drupal, so I need to get  
something relatively simple working fast. Any help or pointers would  
be appreciated!

I have two HABTM many models, recipe\_item and purchase\_item. I need a  
form to designate in my view that any number of purchase\_items or  
recipe\_items can be a component of a given recipe\_item. It looks like  
Ryan B.’ screencast on nested model forms provides a lot of help on  
a similar issue, but I’m having trouble picking apart the logic for my  
issue. Regardless at the moment as a test I’m just trying to get a  
single select on the recipe\_item view to submit the purchase\_item  
association. When I submit I get this error:

PurchaseItem(#20112400) expected, got Array(#102050)

Here is my code:

Models:

class PurchaseItem \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :recipe\_items  
end

class RecipeItem \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :purchase\_items  
end

Controllers are left completely as generated by 2.3 Rails scaffolding.

New recipe\_item View:

# New recipe\_item

\<% form\_for(@recipe\_item) do |f| %\>  
\<%= f.error\_messages %\>

\<%= f.label :name %\>  
 \<%= f.text\_field :name %\>

\<% f.fields\_for :purchase\_items do |n| %\> \<%= n.label :purchase\_item\_id %\> \<%= n.select :purchase\_item\_id, PurchaseItem.all.collect {|a| [a.name, a.id] }%\> \<% end %\>

\<%= f.submit 'Create' %\>

\<% end %\>

\<%= link\_to ‘Back’, recipe\_items\_path %\>

I’m aware this can be DRYed up but like I said right now I just need  
to demonstrate something working for my team. Any help would be  
appreciated!

Thanks,  
Andy

---

<div class="post-metadata">

**Author:** ![andy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/aeb1de/32.png) [@andy](https://www.ruby-forum.com/u/andy)\
**Post date:** [March 18, 2010, 6:57pm UTC](https://www.ruby-forum.com/t/habtm-associations-in-view/185353/2 "2010-03-18T18:57:10Z")

</div>

try this.

\<%= n.select :purchase\_item\_id, PurchaseItem.all.collect {|a| [a.name,  
a.id] }, @recipe.purchase\_item.id %\>

Havent tested it so it may or may not work.
