[英]Linking post to authenticated user - How do I use current_user in the controller? (devise)
I am using the Rails "Getting Started" blog post exercise, and trying to integrate with Devise for authentication and authoring of posts. 我正在使用Rails的“入门”博客文章练习,并尝试与Devise集成以进行文章的身份验证和创作。
When creating an Article, the Author should be the currently logged-in user. 创建文章时,作者应为当前登录用户。
I am getting an error when trying to Create an Article. 尝试创建文章时出现错误。 I know that the error is in my Articles controller, but I can't seem to figure out how to grab the current logged-in Author to kick off the creation of an Article. 我知道该错误出在我的Articles控制器中,但是我似乎无法弄清楚如何抓住当前已登录的Author来开始创建Article。 I believe I did the relationship properly between an Author and an Article. 我相信我正确地处理了作者和文章之间的关系。
Error: undefined method `articles' for nil:NilClass 错误:nil:NilClass的未定义方法“文章”
Author Model: 作者模型:
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
Articles Model: 文章模型:
class Article < ApplicationRecord
belongs_to :author
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end
Articles Controller: 文章负责人:
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
Try removing the @ from @current_author. 尝试从@current_author中删除@。 With devise, current_author is a method that returns the user by session[:user_id] not an instance variable. 通过devise,current_author是一种通过session [:user_id]返回用户而不是实例变量的方法。
Also, try doing one of three things.... 另外,尝试做以下三件事之一...
Change 更改
@author.articles.create(atricle_params) @ author.articles.create(atricle_params)to 至
@author.articles.new(atricle_params) @ author.articles.new(atricle_params)
Move the assignment of the author to the 'new' method as so... 将作者的分配移至“新”方法,如下所示...
\ndef new def新\n @article = Article.new @article = Article.new\n @article.author = current_user @ article.author = current_user\nend 结束\n
Add a hidden_field to your form... 在表格中添加一个hidden_field ...
\n'<%= f.hidden_field :author_id, current_user.id %> '<%= f.hidden_field:author_id,current_user.id%>\n' '
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.