CommentsController#create 中的 NoMethodError 和 LikesController#create 中的 NoMethodError
我遇到了点赞和评论的未定义方法错误。你能帮忙吗?我的仓库分支是 https://github.com/sja-thedude/Blog-App/tree/Add-Forms
likes_controller.rb
class LikesController < ApplicationController
def create
@post = Post.find(params[:post_id])
new_like = current_user.likes.new(
user_id: current_user.id,
post_id: @post.id
)
new_like.update_likes_counter
if new_like.save
redirect_to "/users/#{@post.user_id}/posts/#{@post.id}", notice: 'Success!'
else
render :new, alert: 'Error occured!'
end
end
end
comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
new_comment = current_user.comments.new(
text: comment_params,
user_id: current_user.id,
post_id: @post.id
)
new_comment.update_comments_counter
if new_comment.save
redirect_to "/users/#{@post.user_id}/posts/#{@post.id}", notice: 'Success!'
else
render :new, alert: 'Error occured!'
end
end
private
def comment_params
params.require(:comment).permit(:text)[:text]
end
end
它说
app/controllers/likes_controller.rb:4:in create' 中出现错误并且app/controllers/comments_controller.rb:4:in
创建'
I am having an undefined method error for likes and comments. Can you help? My repo branch is https://github.com/sja-thedude/Blog-App/tree/Add-Forms
likes_controller.rb
class LikesController < ApplicationController
def create
@post = Post.find(params[:post_id])
new_like = current_user.likes.new(
user_id: current_user.id,
post_id: @post.id
)
new_like.update_likes_counter
if new_like.save
redirect_to "/users/#{@post.user_id}/posts/#{@post.id}", notice: 'Success!'
else
render :new, alert: 'Error occured!'
end
end
end
comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
new_comment = current_user.comments.new(
text: comment_params,
user_id: current_user.id,
post_id: @post.id
)
new_comment.update_comments_counter
if new_comment.save
redirect_to "/users/#{@post.user_id}/posts/#{@post.id}", notice: 'Success!'
else
render :new, alert: 'Error occured!'
end
end
private
def comment_params
params.require(:comment).permit(:text)[:text]
end
end
it says error in
app/controllers/likes_controller.rb:4:in create' and app/controllers/comments_controller.rb:4:in
create'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自
ApplicationController
的current_user
方法实际上返回用户列表(尽管技术上仅包含 1 条记录)。将
User.limit(1)
替换为User.take
或User.first
之类的内容。Your
current_user
method fromApplicationController
is actually returning a list of users (although technically containing only 1 record).Replace
User.limit(1)
to something likeUser.take
orUser.first
.