38

I would like to pass the form_for object to a partial:

<%= form_for @price do |f| %>
   ...
   <%= render :partial => "price_page", :object => @price, :as => :f %>
   ...
<% end %>

When I call:

f.radio_button

Brings the error:

undefined method `radio_button' for #<Price:0x3cb1ed0>

How can I use f as I usually would in this partial?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
Harry
  • 1,659
  • 5
  • 19
  • 34

3 Answers3

57

Try passing form object as local <%= render :partial => "price_page", :locals=>{:f=>f} %>

Viren
  • 5,812
  • 6
  • 45
  • 98
Amar
  • 6,874
  • 4
  • 25
  • 23
9

You can pass form builder object as a local variable like below,

<%= form_for @price do |f| %>
     <%= render :partial => "price_page", :locals => { :f => f } %>
<% end %>

in your partial file you will be receiving form builder as a local variable "f", you can use like below,

  <% f.radio_button, {} %>
Mohanraj
  • 4,056
  • 2
  • 22
  • 24
6

I ran across this question trying to figure out how to get a form builder into a partial without an additional form tag. That's the primary use case I could think of for this question, so I'm adding this answer for future visitors.

To solve my problem, I have my form_for in my layout and I render my partial passing only the model. In my partial I use fields_for.

Looks (something) like this:

= form_for @price do |f|
   ...
   = render partial: "price_page", object: @price, as: 'price %>
   ...

Then, my partial has this:

= fields_for price do |f|
   ...
D. Patrick
  • 2,894
  • 26
  • 37