Creating an association with accepts_nested_attributes_for

I have 2 models, Category and LineItemTypes

There are already plenty existing of both, it is now a requirement for
them to be associated. Being many LineItemTypes for every Category.

I have added accepts_nested_attributes_for :line_item_types on Category

I’ve tried using a hidden_field on a form to create a list of existing
associated LineItemTypes:

  • form_for @category do |form|
    %ul#categorised

    • form.fields_for :line_item_types do |line_item_types|
      -categorised.each do |l|
      %li
      =l.description
      =line_item_types.hidden_field :category_id

    =form.submit

If I add an item to that list, I get errors saying that a LineItemType
for that Category can’t be found. I thought
accepts_nested_attributes_for would add the association if it doesn’t
exist. Or is it only for ‘creating’ new records and modifying existing
relationships, not creating new relationships.

a.update_attributes({:line_item_types_attributes => [{:id => 2767}, {:id
=> LineItemType.find(2).id}]})
ActiveRecord::RecordNotFound: Couldn’t find LineItemType with ID=2 for
Category with ID=1

Any ideas without having to write something to traverse the resulting
form params and create the associations? Or an even easier way to
achieving this? I have an existing association with

Probably a silly question. Have you declared the belongs_to and
has_many associations?

Hehe not a silly question, yes, I have, I also got a recommendation to
try using the :inverse_of argument on the relationships too. Which
didn’t haven any effect on the problem.

I’ve come to the conclusion that accepts_nested_attributes_for works
kinda like url_for… Where the presence of ID makes it assume the
relationship exists. Rendering accepts_nested_attributes_for not
suitable for what I want to do.

I’ve worked around this with a before filter:

def find_line_item_types
params[:category][:line_item_types] =
LineItemType.find(params[:category][:line_item_types].collect { |a|
a[0].to_i }) if params[:category] and
params[:category][:line_item_types]
end

Thanks for replying! :slight_smile: