Partial views and forms/ design patterns

25 views
Skip to first unread message

sheamus

unread,
Jun 19, 2012, 7:29:06 PM6/19/12
to rubyonra...@googlegroups.com
Consider a team of players.

I would like to make my _form not include the form header. This would allow me to have different fields available when depending on whether I am editing or creating a new player. It also allows me reuse that form as a partial when building a larger editor page that could say edit 2 players at one.

players/_form
<div>
    <%= f.label :name %>
    <%= f.text_field :name =>
</div>
<div>
    <%= f.label :number %>
    <%= f.text_field :number =>
</div>

players/new.html.erb
<h1>Creating Player</h1>
<%= form_for(@player) do |f| %>
    <%= render 'form' %>
    <div>
        <%= f.label :team %>
        <%= f.text_field :team =>
    </div>
    <%= f.submit %>
<% end %>

players/edit.html.erb
<h1>Editing Player</h1>
<%= form_for(@player) do |f| %>
    <%= render 'form' %>
    <!--
    can't change teams once you have been created.
    <div>
        <%= f.label :team %>
        <%= f.text_field :team =>
    </div>
    -->
    <%= f.submit %>
<% end %>

team/edit_roster.html.erb
<h1>Editing Roster</h1>
<%= form_for(@roster) do |f| %>
    <!-- edit the TwoPlayers object which contains two players -->
    <%= render 'players/form', @roster.first_player %>
    <%= render 'players/form', @roster.second_player %>
    <%= f.submit %>
<% end %>

I use this pattern all the time with MS-MVC/EF/C#.  Is this bad practice in rails? The syntax I have given doesn't quite work, so I guess if I go with this, I'll have to change the new/edit/_form for each one I want to do this with. Even the generate _form won't work, as I don't have access to |f|, in my partial.

What is the 'railsy' way of accomplishing this?

Thanks,
~S

Ryan Buckley

unread,
Jun 19, 2012, 7:39:19 PM6/19/12
to rubyonra...@googlegroups.com
Hey S,

You can always pass your form variable |f| to the partial when you render it. 

i.e.

<%= render partial => 'line_item', :locals => {:new_f => f} %> 

- Ryan 
Message has been deleted

sheamus

unread,
Jun 19, 2012, 10:03:18 PM6/19/12
to rubyonra...@googlegroups.com
Thanks. Yeah I figured I could likely pass in the form variable somehow.

I guess if no one finds my tactic offensive, I'll go the route.

~S

sheamus

unread,
Jun 19, 2012, 10:50:36 PM6/19/12
to rubyonra...@googlegroups.com
Is there a way to change what gets generated by default?
Reply all
Reply to author
Forward
0 new messages