Retrieve Username from User ID

寵の児 提交于 2020-01-05 04:14:28

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/20622630/retrieve-username-from-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!