A
A
Anton Misyagin2015-04-29 00:49:01
Ruby on Rails
Anton Misyagin, 2015-04-29 00:49:01

How to render partial from controller?

Product
.... Category
.... Name
.... Price
, etc.
New product:
display a form with fields:
Category
Name
Price
, etc.
The user selects a category. Depending on the category, category-specific fields are added to the form, such as: diagonal, resolution, interfaces,
or
power, grill function,
or
inkjet / laser printing, print speed,
or
etc.
I would like to make this feature through ajax, so that html is prepared on the server for insertion into an existing form.
I use simple_form in the project.
How should the controller method that sends the Form Piece to the browser approximately look like.
Here is my controller code:

def category_details
    simple_form_for @item do |f|
      render partial: "/items/details_edit", locals: {item_form: f}
    end
  end

undefined method `simple_form_for'

Those. the task is how to send a list of form fields, which I have registered in the parsial without the form itself <form ...></form>?
Or how else to organize the proposed scheme?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Misyagin, 2015-04-29
@sunnmas

Total worked out.
Controller. Action to return detail fields

def category_details
    @item = Item.new
    @item.category = params[:id]
    render 'details_form', layout: false
  end

<%= simple_form_for @adv do |f| %>
логика, которая в зависимости от @item.category, генерит нужные поля с помощью хелперов simple_form
<% end %>

<i>JavaScript:</i>
  $('#поле с выбором категории').change(function(){
    $('#item_details').empty();
    $.get('/cabinet/category/'+$(this).val()+'/details_form', {},
      function(data){
        $(data).children("[type != hidden]").appendTo('#item_details');
      }
    );
  });

#item_details - container for additional fields in the main form. When you select a category, the previously loaded additional fields are cleared. Then a request is sent. We get html with a form, from which we select the core with visible elements ( .children("[type != hidden]") ). We insert into the container.
The fields_for helper was used in the fields generation logic, and accepts_nested_attributes_for was added to the product model to accept child model fields.
Thanks for the help guys)

V
Vladimir, 2015-04-29
@telray

It's not clear why you use simple_form_for in your controller? It should generate the form in partial as-time.
That is, there should be just a partial render, and an item should be passed into it, for which the form is apparently being built.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question