[Rails] DRY up selects in view
Jean-François
jf.web3 at gmail.com
Tue Jun 27 00:11:09 GMT 2006
Hello Bill,
> Here's what I've got:
>
> <% @fields.each do |field_name| %>
> <tr>
> <td>
> <%= field_name.humanize %>
> </td>
> <td>
> <% unless field_name =~ /_id$/ %>
> <%= form.text_field field_name, :size => 40 %>
> <% else %>
> <%= select(:vendor,
> field_name,
> State.find(:all, :order => 'name').collect {|p| [ p.name,
> p.id ] },
> :selected => @vendor.state.id ) %>
> <% end %>
> </td>
> </tr>
> </end>
>
> Right now this works great if I only have "state_id" as the related
> field_name. I could repeat this for every field_name ending in "_id",
> but that's not DRY.
>
> I'd like to allow this to work for any field_names ending in "_id" but I
> need to use the field_name without the "_id" and capitalized as the
> class name. I know I'm thinking about this from a scripting POV, but
> can I get this done?
# field_name = "state_id"
...
class_name = field_name.gsub(/_id$/, '').camelcase
# => "State"
...
class_name.constantize.find :all ...
# => State.find :all ...
...
@vendor.send(class_name.underscore.to_sym)
# => @vendor.state
> Is there a better way to do this?
Not tested, but you get the idea to create your helper.
bye,
-- Jean-François.
--
À la renverse.
More information about the Rails
mailing list