views:

50

answers:

1

I have product and category models, what i want to do is to add a category field inside add new product form (i want it to update in ajax format)

my form is something like this :

<fieldset>
    <legend>
        <%= @form_title %>
    </legend>
    <%= error_messages_for 'theme' , :header_message => "موارد زیر دارای اشکال می باشند، لطفا دوباره بررسی نمایید :" , :message => nil %>
    <ol>
        <% form_for :template , @theme do |t| %>
        <li>
            <%= label :theme , :نام %>
            <%= t.text_field :name %>
        </li>
        <li>
            <%= label :theme , :نام_انگلیسی %>
            <%= t.text_field :en_name %>
        </li>
        <li>
            <%= label :theme , :قیمت %>
            <%= t.text_field :price %>
        </li>
        <li>
            <%= label :theme , :قیمت_ویژه %>
            <%= t.text_field :unique_price %>
        </li>
        <li>
            <%= label :theme , :توضیحات %>
            <%= t.text_area :description %>
        </li>
        <li>
            <%= label :theme , :دسته %>
            <% for category in Category.find(:all) %>
            <%= check_box_tag "template[category_ids][]" , category.id , @theme.categories.include?(category) %>
            <span class="category_name"><%= category.name %></span>
            <br/>
            <% end %>
        </li>
        <p id="template_cat">
        </p>
        <p class="cat">
            <% fields_for "template[cat_attributes][]" , @theme do |cat_form| -%>
            <li>
                <%= cat_form.text_field :name %> اضافه کردن دسته جدید
            </li>
            <% end -%>
        </p>
        <li>
            <%= label :theme , :عکس_قالب %>
            <%= t.file_field :photo %>
        </li>
        <li>
            <%= submit_tag "#{@form_title}" %>
        </li>
        <% end %>
    </ol>
</fieldset>

in p tag with cat class name is the code for adding a new category

<p class="cat">
    <% fields_for "template[cat_attributes][]" , @theme do |cat_form| -%>
    <li>
        <%= cat_form.text_field :name %> اضافه کردن دسته جدید
    </li>
    <% end -%>
</p>

its working in normal way if i submit the form, but i want add this ability to add a new category without submitting the form first. how can i do that

A: 

This will not be possible since the fields_for method does not create a new form, but only adds new <input> elements to the main form, in your case the template form

So the solution is to extract the <%= cat_form.text_field :name %> اضافه کردن دسته جدید into a new form, and since you want it to use Ajax you have to create a remote_form_for as described in the Rails API

eroi