2017-09-14 1 views
0

"Getting Started"블로그 게시물 연습을 사용 중이며 게시물의 인증 및 작성을 위해 Devise와 통합하려고합니다.인증 된 사용자에게 게시물 연결 - 컨트롤러에서 current_user를 어떻게 사용합니까?

아티클을 만들 때 작성자는 현재 로그인 한 사용자 여야합니다.

기사 작성 중 오류가 발생했습니다. 나는 오류가 내 기사 컨트롤러에 있다는 것을 알고 있지만, 현재 로그인 한 작성자가 기사 작성을 시작하는 방법을 파악할 수없는 것 같습니다. 나는 내가 저자와 기사 사이의 관계를 적절하게했다고 생각한다.

오류 : 무기 호에 대한 정의되지 않은 메서드`기사 'NilClass

저자 모델 :

class Author < ApplicationRecord 
    has_many :articles 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

end 

제품 모델 :

class Article < ApplicationRecord 
    belongs_to :author 
    has_many :comments, dependent: :destroy 
    validates :title, presence: true, 
    length: { minimum: 5 } 
end 

기사 컨트롤러 :

class ArticlesController < ApplicationController 
    def index 
    @articles = Article.all 
    end 

    def show 
    @article = Article.find(params[: id]) 
    end 

    def new 
    @article = Article.new 
    end 

    def edit 
    @article = Article.find(params[: id]) 
    end 

    def create 
    @author = @current_author 
    @article = @author.articles.create(article_params) 

    if @article.save 
     redirect_to @article 
    else 
     render 'new' 
    end 
    end 

    def update 
    @article = Article.find(params[: id]) 

    if @article.update(article_params) 
     redirect_to @article 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    @article = Article.find(params[: id]) 
    @article.destroy 

    redirect_to articles_path 
    end 

    private 

    def article_params 
    params.require(: article).permit(: title,: text,: author) 
    end 
end 
+0

는 사용'@author = current_author' – sa77

답변

0

시도 레모 @current_author에서 @를 읽는 중입니다. devise를 사용하면 current_author는 인스턴스 변수가 아닌 세션 [: user_id]별로 사용자를 반환하는 메서드입니다. 또한

  1. 변경 .... 세 가지 중 하나를 수행

    @author.articles.create(atricle_params)

  2. @author.articles.new(atricle_params)
    로 이동합니다 '새로운'방법으로 그래서 ...

    에 대한 저자의 할당을 시도
     
    def new 
        @article = Article.new 
        @article.author = current_user 
    end 
    
  3. ... 폼에 hidden_field 추가

     
    '<%= f.hidden_field :author_id, current_user.id %> 
    
    '

+0

감사합니다! @current_author보다는 current_author를 사용하는 첫 번째 제안이 효과가있었습니다. – chipsandal

+0

기꺼이 도와 드리겠습니다. –

관련 문제