私は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
ちょうどありがとう '@author = current_author' – sa77