Replace id with name in collection_select

In my application I have a collection_select in my members table, the members table only contains IDs. It has user_id, project_id, role_id, etc.

I want to show the name of the members in collection_select. But I only have user_id in the members table, how can I show the names from the user table as parameters?

<%= collection_select(nil, :member_id, members, :id, :user_id,
                 {:prompt   => "Select a member"}) %>

      

Now the selection window displays parameters 1,2,3,4, etc. it should be name1, name2, from the user table.

Does this have any experience?

+2


source to share


1 answer


First of all, you need to add a new method to the member model:

class Member < ActiveRecord::Base
  belongs_to :user
  def member_name
    user.name
  end
end

      



Then change the argument text_method

to member_name

:

<%= collection_select(:member, :member_id, members, :id, :member_name,
                 {:prompt   => "Select a member"}) %>

      

+3


source







All Articles