user3658789
user3658789

Reputation: 5

Display user_id to username

Rails newbie here. I'm trying to display a user's name when they post something. However, it keeps on showing the user_id (integer). I would like to display their actual name. I wired everything correctly. Here is the code. Thanks.

in post/[email protected] will show an undefined method error.

    <%= render 'layouts/header' %>

    <!--posts table!-->
    <div class="container">
      <% @posts.each do |post| %>
        <div class="panel panel-info">
          <div class="panel-heading">
            <h3 class="panel-title">
              <%= post.title %>
          <div class="pull-right">
            <%= @user.username %> |
            <%= time_ago_in_words(Time.now) %>
          </div>
        </h3>
      </div>  
      <div class="panel-body">
        <%= post.description %>
      </div>
    </div>
  <% end %>

Upvotes: 0

Views: 115

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

To give you some more input - what Pavan described is all to do with the ActiveRecord associations in Rails:

#app/models/post.rb
belongs_to :user

This creates another method on your parent object (@post.user), which will populate with the data referenced by the foreign_key in your parent object. For example, you have user_id in your Post model - that will be translated into .user for use in your view

This means you'll be able to call @post.user.name to get the username or whatever attribute you have in your User model

--

Delegate

But there's more!!

You'll benefit from the .delegate method - which basically allows you to treat methods in an associated controller as the parent's:

#app/models/post.rb
belongs_to :user
delegate :name, to: :user, prefix: true #-> creates post.user_name

This means you'll be able to call the delegated methods on your parent model directly (like how you've got it right now)

Upvotes: 1

Pavan
Pavan

Reputation: 33542

It should be

<%= post.user.username %>
<!--posts table!-->
<div class="container">
<% @posts.each do |post| %>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">
<%= post.title %>
<div class="pull-right">
<%= post.user.username %> | #here
<%= time_ago_in_words(Time.now) %>
</div>
</h3>
</div>  
<div class="panel-body">
<%= post.description %>
</div>
</div>
<% end %>

<%= post.user_id %> will always give the integer value(user_id is integer).If you want to show the associated username,then you have to do <%= post.user.username %>

Note: Sorry for the format.I like it to be like that.

Upvotes: 1

Related Questions