从用户标识中检索用户名

嗨,我有一个post模型,其中post属于用户,用户has_manypost。

posts表有一个user_id

在我的节目帖中,我有:

 

我得到用户ID谁发布这个工作正常。 当Users表包含列User_name时,如何获取用户名?我是否需要将post_id添加到Users或?

  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 

在我的post控制器我有

 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 

如果post belongs_to user那么你可以这样做:

 <%= post.user.user_name %> 

并且您不需要将post_id添加到用户,因为它是belongs_to user而不是user belongs_to post 。 当post belongs_to user ,你在posts表中有user_id ,外键。

希望这是有道理的。

更新:

undefined method 'username' for nil:NilClass获取undefined method 'username' for nil:NilClass的原因undefined method 'username' for nil:NilClass是因为您创建post的方式未附加关联的user对象。 既然您正在使用devise ,那么您可以做些什么来完成这项工作:

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

我没有在上面的create动作中包含无关紧要的行。

current_user.posts.build(params[:post])current_user构建一个post对象,这样构建的post就会在这种情况下获得关联用户current_user 。 有了这个,你将能够做到:

 post.user.username