Search code examples
ruby-on-rails-5actionview

Display full name in rails select form defined in model


I am working on rails 5 app. The issue I am facing is I am defining a drop down to select the user from another table in blogs form.The associations are as below.

blog.rb

has_many :blogs

def set_full_name
 self.full_name = [first_name, last_name].join(' ')
end

user.rb

belongs_to :user

The problem is in this select form instead of displaying just the first_name in the drop-down list, I was to show the full_name of the user which I have defined in the user model. How can I do that?

<%= form.collection_select :user_id, User.all, :id, :first_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>

Solution

  • You're calling :first_name for the text property. Use :full_name

    <%= form.collection_select :user_id, User.all, :id, :full_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>