jessieot
jessieot

Reputation: 1

Rails tutorial - displaying username instead of user_id

In the Rails Tutorial there is a great chapter on creating a toy app with users and microposts. However, when editing the microposts, I can only edit user_id which is a numeric value, not user name. Is there a simple way to enforce displaying user's name instead of user's id in the app? I've looked app/views/microposts/_form.html.erb and it says:

<div class="field">
<%= f.label :user_id %><br>
<%= f.number_field :user_id %>
</div>

What should I change to be able to select the users by name instead of the id?

Upvotes: 0

Views: 263

Answers (2)

Andrew
Andrew

Reputation: 238717

The feature you're looking for is called a collection_select. http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

f.collection_select :user_id, User.all, :id, :username

Upvotes: 0

MarsAtomic
MarsAtomic

Reputation: 10673

Try using a select helper rather than a number_field.

<%= f.collection_select(:user_id, @users, :id, :first_name) %>

In your controller, you'd need the following line (or something similar):

@users = User.all

If you want to display each user's full name, you'd need to create a method in user.rb to concatenate first and last names, like so:

def fullname
    fullname = "#{last_name}, #{first_name}"
end

Your select would then use the method name, like this:

<%= f.collection_select(:user_id, @users, :id, :fullname) %>

You should probably take some time to read up on all the different form helpers.

Upvotes: 1

Related Questions