2017-09-14 4 views
0

私はRailsの「Getting Started」ブログ記事の練習問題を使用しており、投稿の認証とオーサリングのためにDeviseと統合しようとしています。認証されたユーザーに投稿をリンクする - コントローラでcurrent_userを使用するにはどうすればよいですか?

アーティクルを作成するとき、作成者は現在ログインしているユーザーである必要があります。

記事を作成しようとするとエラーが発生します。私はエラーが私の記事のコントローラにあることを知っていますが、私は現在のログインした著者が記事の作成を開始する方法を把握していないようです。私は著者と記事の関係を適切にしたと信じています。

エラー:nilのための未定義のメソッド `記事: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. 変更.... 3つのいずれかをやって

    @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

うれしい私は助けることができました。 –

関連する問題