2014-12-13 2 views
0

각 기사에 user_ids 추가 (유증) :나는 사용자 모델을

devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_secure_password has_many :articles

그리고 User 내 스키마는 다음과 같습니다 이들의

create_table "users", force: true do |t| t.string "first_name" t.string "last_name" t.string "email" t.string "password_digest" t.datetime "created_at" t.datetime "updated_at" t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" end

절반이 고안 출신 보석. 그래서 내가 성취하고자하는 것은 각 기사에 그것에 할당 된 저자가있는 것입니다 (first_name + last_name).

belongs_to :topic 
belongs_to :user 

def author 
    "#{self.user_id.first_name} #{self.user_id.last_name}" 
end 

그리고 문서 컨트롤러의 내 행동은 다음과 같습니다 :

내 문서 모델 같은 외모

def create 
@article = Article.new(article_params) 
@article.user = current_user 
if @article.save 
    #@article.user = session[:user_id] 
    flash[:notice] = "Article has been uploaded" 
    redirect_to(:action => "show", :id => @article.id) 
else 
    flash[:notice] = "Please fill in all fields." 
    render("new") 
end 
end 

그리고 내 쇼보기에서 <p><%[email protected]%></p>을 할 경우, 그것은라는 오류가 정의되지 않은 메서드 - 'first_name'

각 기사에 작성자를 추가하려면 어떻게합니까? 대신 저자 방법을 self.user_id.first_name.in의

+0

, 나도 몰라. – xoshi827

답변

0

사용 self.user.first_name
그리고 당신은이 경우 다음
사용 @의 artilce.user_id 오티 사용 USER_ID를 원하는 경우 @ article.user = CURRENT_USER는 괜찮습니다 = 여기 괜찮

+0

안녕하세요. 나는 원래 가지고있는 코드에 간섭하는 문제를 가지고있다. 나는'Access' 컨트롤러에 코드를 가지고 있습니다 : – xoshi827

+0

'def 시도 _login params [: email] .present? && params [: password] .present? found_user = User.where (: 이메일 => PARAMS [: 이메일). 제 경우 found_user authorised_user = found_user.authenticate (PARAMS [: 암호]) 단부 단부 경우 authorised_user 세션 [: USER_ID = authorised_user .id 세션 [: email] = authorised_user.email 플래시 [: notice] = "사용자가 로그인했습니다" redirect_to (: controller => "articles", : action => 'index') 끝 ' – xoshi827

+0

당신의 원래 문제와 관련이 없습니다. 그런데 당신이 지금 직면하고있는 문제를 설명 할 수 있습니다.이 방법과 의견을 작성하면 아무 것도 결론 지을 수 없기 때문에 ... –

0

당신이 그것을 어떻게입니다 current_user.id :

user.rb을

has_many :items 

article.rb

내가 만드는 행동에 `@article.user_id = current_user`를 사용하는 경우는
belongs_to :user 

articles_controller.rb 또한

def create 
    @article = Article.new(params[:article].permit(:name, ...)) 
    @article.user_id = current_user.id 
    if @article.save 
     flash[:notice] = 'article created' 
     redirect_to @article 
    else 
     render 'new' 
    end 
end 
관련 문제