Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-4grouped-collection-select

Rails collection_select and Foreign_key


Following is my code,

<%= f.collection_select :event_member_id, EventMember.all, :id, :company_member_id, :prompt => "Please select" %>

Here :company_member_id is foreign_key in EventMember class, i wanted to display text_method as company_member_email instead of company_member_id,

So my collection_select should be like below,

<%= f.collection_select :event_member_id, EventMember.all, :id, :'company_member.email', :prompt => "Please select" %>

How to achieve above...!!!


Solution

  • In EventMember modal :-

    def company_member_email
      return self.company_member.email unless self.company_member.nil?
      ""
    end
    

    And the collection as:-

    <%= f.collection_select :event_member_id, EventMember.all, :id, :company_member_email, :prompt => "Please select" %>