ruby-on-railsrubyruby-on-rails-3activeview

Pass instance or local variable from layout to view in Rails


I'm trying to set up a rather complex form using form_for. This form needs to be in multiple views, where some fields would be available across all actions and other fields are specific to each individual actions.

I thought that in order to save myself code duplication, I would use a layout to render the general part, like this:

# layout.html.erb
<%= form_for @instance do |f| %>
  <%= f.text_field :foo %><!-- This field needs to be available in all views -->
  <...><!-- Additional non-form related html -->
  <%= yield %>
  <%= f.submit %>
<% end %>

# first_view.html.erb
<% f.fields_for :bar do |b| %>
  <%# Fields %><!-- These fields should only be available in first_view -->
<% end %>

# second_view.html.erb
<% f.text_field :baz %><!-- This field should only be available in second_view -->

Now, the problem is that I can't pass f as a local variable from the layout to the view. I can't even set an instance variable (eg. @f = f) and access it in the views.

How could I do this? Any suggestions for a better implementation would be welcome.


Solution

  • In the end, I decided to go with the easy, fool-proof solution. I've now moved the form_for into the individual views, and put the general fields in a partial. What it means is that I have to duplicate form_for as well as the rendering of the partial, but I can live with that.