【问题标题】:Retrieve Username from User ID从用户 ID 中检索用户名
【发布时间】:2013-12-16 22:54:17
【问题描述】:

您好,我有一个帖子模型,其中一个帖子属于一个用户,一个用户拥有多个帖子。

posts 表有一个 user_id

目前在我的秀贴中我有:

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

我得到了使帖子正常工作的用户 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

在我的帖子控制器中,我有

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

【问题讨论】:

  • 如果您没有客户实际为 Web 服务 api 付费,请去掉那些 format.json 行。它们仅用于教程;真正的项目不应该有过多的投机代码

标签: ruby-on-rails show relationships


【解决方案1】:

如果postbelongs_touser那么你可以这样做:

<%= post.user.user_name %>

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

希望这是有道理的。

更新:

您获得undefined method 'username' for nil:NilClass 的原因是因为您创建帖子的方式没有附加关联的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

【讨论】:

  • 当我尝试 nil:NilClass 的未定义方法 `username' 时出现此错误
  • 不应该是user_name而不是username吗?注意下划线。
  • 它在我的用户名对不起我在第一篇文章中犯了一个错误
  • 您能否发布您的user 和post 模型以及呈现相关视图的控制器操作。
  • 更新了我与他们的第一篇文章
猜你喜欢
  • 2023-03-12
  • 2012-01-06
  • 2013-12-11
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 2014-04-06
  • 1970-01-01
相关资源
最近更新 更多