Search code examples
ruby-on-railsnested-formsnested-form-for

Nested_form gem: passing parameters with link_to_add



I met a problem with nested_form gem.
I have 5 models: Category, Group, Parameter, Offer and Value. So Offers belongs to Category, Values belongs to Offers and Parameters, Parameters are united in Groups, and Groups belongs to Category.
Typical example is like

Category: car
  Group: engine parameters
    Parameter: volume
    Parameter: power
  Group: producer
    Parameter: producer_name
    Parameter: year
    Parameter: country

Category: bicycle
  Group: technical parameters
    Parameter: wheel diameter
    Parameter: weight
  Group: producer
    Parameter: producer_name
    Parameter: year
    Parameter: country

And values of this parameters belongs to offers. Maybe looks complicated, but it seems to me I illustrated it quite clearly. I want to build form, which allows to create many Offers during user registration. Categories, parameters and groups are fixed. Now my template is:

= simple_nested_form_for @user
  Category.all.each do |category|
    span= category.name
    = f.simple_fields_for :offers do |f_offer|
    = f_offer.input :category_id, :as => :hidden
    - category.groups.each do |group|
      span= group.name
      - if f_offer.object.values.where("parameter_id IN (?)", group.parameters).empty?
        - group.parameters.each do |parameter|
          - variant.values.build(:parameter_id => parameter.id)
      / In this partial inputs for offer values in format parameter_name: input_field
      = render :partial => 'values', :locals => { :f_offer => f_offer,
          :f_group => group }
    = f_variant.link_to_remove t("views.remove_variant")
  = f.link_to_add "Add offer", :offers

It works almost fine, but the problem is when I click "Add offer" link - form is added with parameters of last category. So with examples I've given above, when I click "Add offer" for Car category - I see bunch of parameters not for car, but for bicycle! Looks like I should pass category to simple_fields_for or something like that, but I don't have any idea how to do it.
Can anyone help me?


Solution

  • I found a workaround for this problem: I've added a new action like "generate_form", where I create new User and add new Offer to it, and in view I generate form for this new User with nested fields for it's Offer.

    When user clicks "Add offer" link, I execute ajax request to this generate_form action, passing category id, but in response I get , so I cut nested form, with jQuery it's quite easy, and also I need to replace zero offer id with randomly generated, both of these are performed by ajax "done" callback.

    Maybe quite ugly way, but finally it works. If anyone can provide another solution - I will be glad to see it.