Use accepts_nested_attributes_for for new object without showing the user all the child records

285 Views Asked by At

I am trying to use accepts_nested_attributes_for in a slightly irregular way.

An estimate has many moneys:

class Estimate
  has_many   :moneys           , :as => :moneyable, :dependent => :destroy
  accepts_nested_attributes_for :moneys
  ...
end

But in an estimate's edit form, I don't want the user to see nested fieldsets of all the previous moneys' values. I only want her to see one set of empty money fields. From Rails' point of view, the estimate will have a nice history of all the previous moneys but from the user's point of view she will only see some empty fields which she can fill in if she wants to change the estimate.

= f.semantic_fields_for @estimate.moneys.build do |money|
  = money.input :quantity 
  ...

Normally you'd do f.semantic_fields_for :moneys, but that will display all the previous child moneys records. I could also use javascript to generate fields on the fly, but I want to avoid that because it's another button for the user to have to click on. Hence I'm building a new object in the form (which I'd probably eventually move to the controller, for decency's sake).

Trouble is, if I build a new object as in the form above, I won't get the accepts_nested_attributes_for goodness because Rails won't pass the money params as :money_attributes. It'll pass them as :money:

Parameters: {..."estimate"=>{"book_id"=>"1418", ...,  "money"=>{"quantity"=>"321",...}}, "commit"=>"Save", "id"=>"67"}

I can faff around in the controller, adding the parent's id (and type, in this case, because it's a polymorphic relationship), but that is ugly. Am I missing a way that I can use ANAF whilst building a new object and not showing the user all the child records in the view?

1

There are 1 best solutions below

2
On BEST ANSWER

Okey, I understand the problem. There is few possible solutions.

  • One is you manually manipulate the form with raw html attribute
  • You can check if the form builder object's object is new a record or not?.

Then condition may looks like:

= f.semantic_fields_for @estimate.moneys.build do |money|
  - if money.object.new_record?
     = add your form attribute here

So this will only let you to show the form to create a new nested record for your form.

I hope this answer will at least give an idea.