【发布时间】:2019-12-06 21:52:06
【问题描述】:
我正在尝试在我的 Web 应用程序上的帖子中添加 cmets 部分,但在保存评论时出现错误
我一直在按照教程将 cmets 部分添加到我的帖子中,并且在我开始使用我的应用程序时一直在进行修改。我对 Rails 还是比较陌生,我还在学习。我了解错误消息告诉我的内容,但我不确定如何继续
评论控制器:
class CommentsController < ApplicationController
def create
@micropost = Micropost.find_by(id: params[:id])
@comment =
@micropost.comments.create(params[:comment].permit(:body))
end
end
微帖子控制器:
class MicropostsController < ApplicationController
before_action :logged_in_user, :upvote, :downvote, only:
[:create, :destroy]
before_action :correct_user, :upvote, :downvote, only:
:destroy, allow_destroy: true
def create
@micropost = current_user.microposts.build(micropost_params)
@maximum_length = Micropost.validators_on( :content,
:headline).first.options[:maximum]
if @micropost.save
flash[:success] = "Article Posted"
redirect_to root_url
else
@feed_items = []
render 'articles/home'
end
end
def destroy
@micropost.destroy
flash[:success] = "Micropost deleted"
redirect_to request.referrer || current_user
end
def show
@micropost = Micropost.find(params[:id])
end
private
def micropost_params
params.require(:micropost).permit(:content, :headline)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
在帖子上呈现评论表单:
<%= form_for([@micropost, @micropost.comments.build]) do |f| %>
<br>
<p>
<%= current_user.name %>
<%= f.text_area :body %>
</p>
<br>
<p>
<%= f.submit %>
</p>
<% end %>
评论模型:
class Comment < ApplicationRecord
belongs_to :micropost
end
微博模型:
class Micropost < ApplicationRecord
acts_as_votable
has_many :comments
belongs_to :user
validates :user_id, presence: true
validates :headline, presence: true, length: { maximum: 200 }
validates :content, presence: true, length: { maximum: 5000 }
end
表格:
create_table "comments", force: :cascade do |t|
t.string "name"
t.text "body"
t.bigint "microposts_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "micropost_id"
t.index ["microposts_id"], name:
"index_comments_on_microposts_id"
end
create_table "microposts", force: :cascade do |t|
t.text "content"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "headline"
t.index ["user_id", "created_at"], name:
"index_microposts_on_user_id_and_created_at"
t.index ["user_id"], name: "index_microposts_on_user_id"
end
表单正在微博显示视图上呈现。我可以很好地看到表格。
当我按下保存对帖子的评论时,我收到一条错误消息,指出 undefined method comments for nil:NilClass,它突出显示了评论控制器和行 @comment = @micropost.comments.create(params[:comment].permit(:body))
我知道可能应该在某个地方为 cmets 提供一种方法。我看的教程没有添加任何类似的东西。所以我不确定我需要修改一些现有的代码,还是需要在某处添加一个名为 cmets 的方法?
【问题讨论】:
-
您的问题,如错误所示,是
@micropost是nil和nil不响应comments。显然,Micropost.find_by(id: params[:id])返回零。这意味着params[:id]是nil或持有不是id的Micropost的值。 -
进入 cmets_controller 的参数是什么?
标签: ruby-on-rails ruby comments