2013-12-16 5 views
1

안녕하세요 저는 게시물이 belongs_to 인 사용자와 사용자 has_many 게시물이있는 게시물 모델이 있습니다. 사용자 이름 검색 사용자 이름

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

내가이 잘 작동 포스트를 만드는 사용자 ID를 얻을 :

포스트 테이블은 내가 가진 내 공연 게시물에 순간에 USER_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

실제로 웹 서비스 API를 지불하는 클라이언트가 없다면 format.json 행을 꺼내십시오. 튜토리얼을위한 것입니다. 실제 프로젝트에 과도한 추측 코드가 있어서는 안됩니다 – Phlip

답변

2

다음 postbelongs_touser 경우에 나는 없다 :

<%= post.user.user_name %> 

을 그리고이기 때문에 더는 사용자에 post_id을 추가 할 필요가 없습니다 postbelongs_touser 아니요 userbelongs_topost. postbelongs_touser 인 경우 user_id이고 외래 키는 posts입니다.

희망적입니다.

업데이트 :

당신이 게시물을 작성하는 방법은 관련 user 객체를 부착하지 않기 때문에 당신이 undefined method 'username' for nil:NilClass을 받고있는 이유입니다.

# 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 라인을 포함하고 있지 않다 : 여기 devise을 사용하고 있기 때문에 당신이 일을 위해 할 수있는 일이다.

current_user.posts.build(params[:post])current_user에 대한 post 객체, 내장 post이 경우 current_user에 연결된 사용자를 얻을이 방법을 구축합니다. 이를 통해 다음을 할 수 있습니다.

post.user.username 
+0

NIL에 대해 정의되지 않은 메소드'username '을 시도 할 때이 오류가 발생합니다 : NilClass – user2527785

+0

'username'이 아닌'user_name'이 될까요? 밑줄에 유의하십시오. – vee

+0

내 사용자 이름 사용자 이름 미안 내 첫 번째 게시물에서 실수를했습니다. – user2527785

관련 문제