user2527785
user2527785

Reputation: 117

Retrieve Username from User ID

Hi I have a posts model where a post belongs_to a user and a user has_many posts.

The posts table has a user_id

At the moment in my show posts I have:

<td><%= post.user_id %></td>

I get the users id who makes the post this works fine. How can I get the username when the Users table contains a column User_name do I need to add post_id to Users or?

 class User < ActiveRecord::Base

 devise :database_authenticatable, :registerable,
 :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :username, :password_confirmation, :remember_me

 has_one :profile
 has_many :orders
has_many :posts

end

  class Post < ActiveRecord::Base
    belongs_to :user
    attr_accessible :content, :title, :user_id
    validates :title, presence: true,
                length: { minimum: 5 }
 end

In my posts controller I have

def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
respond_to do |format|
  if @post.save
    format.html { redirect_to @post, notice: 'Post was successfully created.' }
    format.json { render json: @post, status: :created, location: @post }
  else
    format.html { render action: "new" }
    format.json { render json: @post.errors, status: :unprocessable_entity }
  end
  end
 end

Upvotes: 1

Views: 2599

Answers (1)

vee
vee

Reputation: 38645

If post belongs_to user then you can do:

<%= post.user.user_name %>

And no you don't need to add post_id to Users because it's the post that belongs_to user not user belongs_to post. When post belongs_to user, you have user_id, foreign key in posts table.

Hope this makes sense.

Update:

The reason you are getting undefined method 'username' for nil:NilClass is because the way you are creating post is not attaching the associated user object. Since you are using devise here is what you can do to make this work:

# app/controllers/posts.rb

def create
  @post = current_user.posts.build(params[:post])
  # @post.user_id = current_user.id # Remove this line
  ...
end

I'm not including the irrelavant lines in create action above.

The current_user.posts.build(params[:post]) builds a post object for the current_user, this way the built post gets the associated user in this case current_user. With this you will be able to do:

post.user.username

Upvotes: 3

Related Questions