将帖子链接到经过身份验证的用户 - 如何在控制器中使用current_user? (设计)
我正在使用Rails的“入门”博客帖子练习,并尝试与Devise进行身份验证和创作。将帖子链接到经过身份验证的用户 - 如何在控制器中使用current_user? (设计)
创建文章时,作者应该是当前登录的用户。
尝试创建文章时出现错误。我知道错误出现在我的Articles控制器中,但似乎无法弄清楚如何抓取当前登录的作者来启动文章的创建。我相信我在作者和文章之间做了适当的关系。
错误:未定义的方法`的文章对零: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
尝试雷莫从@current_author中@。通过设计,current_author是一种通过session [:user_id]而不是实例变量返回用户的方法。
另外,尽量做的三件事情一个....
-
变化
@author.articles.create(atricle_params)
到@author.articles.new(atricle_params)
-
移动笔者的分配,以“新”方法,所以......
def new @article = Article.new @article.author = current_user end
-
一个hidden_field添加到您的形式...
'<%= f.hidden_field :author_id, current_user.id %>
'
谢谢!第一个使用current_author而不是@current_author的建议奏效了。 – chipsandal
很高兴我能帮到你。 –
只是用'@author = current_author' – sa77