开发者

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.


Could you extract the form into a partial which takes the ':bar' or ':baz' fields as a local which is passed by the view rendering that partial?

i.e.

render :partial => 'complex_form' :locals => { :text_field_param => :bar }

The above line would be called in first_view and the partial would contain all the form logic and markup using 'text_field_param' for the specialized text field.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜