DRY up selects in view

Here’s what I’ve got:

<% @fields.each do |field_name| %>

<%= field_name.humanize %> <% 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 %>

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?

Is there a better way to do this?

Thanks,
Bill

Hello Bill,

<% else %>

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.

Tested and works. Thanks for the help. I’m not sure about the last
step though. Why class_name.underscore ?

Bill

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs