I'm new to Rails development, so please bear with me. I'm creating a view that has several fields on it that look very similar. It's just begging to be refactored somehow but I haven't been able to figure it out. See code sample below:
<%= form_for(@tapelog) do |f| %>
<div class="container">
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :client %开发者_Python百科>
</div>
<div class="span-8 last">
<%= f.collection_select :client_id, Client.find(:all), :id, :name,
{ :prompt => "Select a Client..." },
{ :class => "automatixSelect" } %>
</div>
</div>
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :employer %>
</div>
<div class="span-8 last">
<%= f.collection_select :employer_id, Employer.find(:all), :id, :name,
{ :prompt => "Select an Employer..." },
{ :class => "automatixSelect" } %>
</div>
</div>
....
<% end %>
There are about 7 fields like that. I tried to put them all into partials just so I could reduce the clutter on this page but that errors out because 'f' is not defined. Any ideas on how I could reduce some of the clutter here? Any other tips in general on Ruby refactoring would also be welcome.
Thanks, -- A.
If you want to use the 'f' in the subsequent partials, pass it as a parameter
<%= render :partial => :some_partial, :locals => { :f => f } %>
The first thing I'd do is rename the "f" local variable to "form" for clarity. Then, extracting the code to a partial is reasonable:
<div class="field span-16">
<div class="span-8 labelRight">
<%= form.label :employer %>
</div>
<div class="span-8 last">
<%= form.collection_select :employer_id, Employer.find(:all), :id, :name,
{ :prompt => "Select an Employer..." },
{ :class => "automatixSelect" } %>
</div>
</div>
It looks to me like this is a belongs_to relationship, so I might create a partial called "belongs_to" and render it like:
<%= render :belongs_to, :parent => :employer, :form => form %>
The idea is we'll have a local named "parent" that we can alter in the partial. Note that I used the shorthand partial syntax. It's the same as:
<%= render :partial => :belongs_to, :locals => { :parent => :employer, :form => form } %>
<div class="field span-16">
<div class="span-8 labelRight">
<%= form.label parent %>
</div>
<div class="span-8 last">
<%= form.collection_select :"#{parent}_id", parent.to_s.capitalize.constantize.find(:all), :id, :name,
{ :prompt => "Select an #{parent.to_s.capitalize}..." },
{ :class => "automatixSelect" } %>
</div>
</div>
精彩评论