Kim
Kim

Reputation: 2156

dealing with form object when rendering partial via rjs

I have a form where based on the value selected by the user in a drop down list, the rest of the form is displayed via a partial.

Model:

Book has many supplierdetails
Supplierdetails belongs to Book

form code

<% fields_for @book do |f| %>


 Catalogue Number: <%= f.text_field :BK_CAT_NUM %>

  <% f.fields_for :supplierdetails do |builder| %>
   Supplier Type:
    <%= builder.select(:SUP_TYPE, 
         [['A', 'A'],
          ['B', 'B'],
        ],{ :prompt => "Please select"}       
      ) %>


    <%= observe_field("book_supplierdetails_attributes_0_SUP_TYPE", 
      :url => { :controller => 'books', :action => :display_ab_details },
      :with => "'id='+value") %>

    <div id="div1">  </div>



  <% end %>
<% end %>

controller method

  def display_ab_details
    supplier_type = params[:id]
    if supplier_type == "A"
      render :update do |page|
        page['div1'].replace_html :partial => 'books/test_partial'
      end
    end
  end

books/_test_partial.html.erb

Production Method: </label> <%= builder.select(:SUP_PROD_METHOD, [
        ['prod_1', 'prod_1'],
        ['prod_2', 'prod_2'],
      ],{ :prompt => "Please select"}
    ) %>

The partial is not displayed and I believe it is because of the form object.

If 'books/_test_partial.html.erb' contains plain text, it is displayed correcly.

How do I deal with form object when rendering partial via rjs?

Upvotes: 0

Views: 175

Answers (1)

mrbrdo
mrbrdo

Reputation: 8258

I don't have an actual answer for your question, but since RJS is not in Rails anymore since v3.1, you're better off jumping the bandwagon and using unobtrusive javascript for things like this, as it is now the preferred way to do things like this. It will be easier to get help as well, since most Rails developers don't use RJS nowadays (actually, not a lot of people used it before either).

Some information on that can be found here: http://wowkhmer.com/2011/09/19/unobtrusive-ajax-with-rails-31/

Also, what you are doing probably doesn't work because you're trying to use builder in the partial. You can't do that. You need to either use fields_for or simply output the inputs HTML yourself, but be careful to provide the correct name for the inputs. Also I'm pretty sure if you look into your server log you will see an error on that line where you're trying to use builder. There is absolutely no way in Rails to use the builder of the original form in a partial that is being rendered later via an AJAX request.

There is also a Railscasts where Ryan does something similar to what you're doing, but he is not using RJS. I believe it is this episode or something related to it: http://railscasts.com/episodes/75-complex-forms-part-3

Upvotes: 1

Related Questions