2013-12-16 72 views
1

您好我有一个职位模型,其中职位belongs_to用户和用户has_many职位。从用户ID检索用户名

的职位表有一个user_id的

此刻在我的节目的帖子,我有:

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

我得到的用户ID谁做这工作正常后。当用户表包含列User_name时,我如何获取用户名?是否需要向用户添加post_id或?

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 
+0

如果你没有客户端实际上为web服务api付费,那么把这些format.json行出去。他们只是用于教程;真正的项目不应该有过多的投机代码 – Phlip

回答

2

如果postbelongs_touser那么你可以做:

<%= post.user.user_name %> 

而且没有你不需要添加post_id给用户,因为它是postbelongs_touser不是userbelongs_topost。当postbelongs_touser,你有user_id,外键在posts表中。

希望这是有道理的。

更新:

您得到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行动irrelavant线。

current_user.posts.build(params[:post])建立一个post对象为current_user,这样内置post得到在这种情况下current_user相关的用户。有了这个,你将可以做到:

post.user.username 
+0

当我尝试未定义的方法'用户名'为零时,我得到这个错误:NilClass – user2527785

+0

不应该是'user_name'而不是'username'?请注意下划线。 – vee

+0

它在我的用户名抱歉,我在我的第一篇文章中犯了一个错误 – user2527785