当我试图删除注释时,出现了一个错误,即“未定义的方法‘破坏’表示为nil:NilClass”。
当我向不同的微博添加注释时,所有评论micropost_id都是相同的,并在所有微博下面显示所有注释。
如果有人能帮我在微博上添加评论,我将不胜感激。我已经试了两个星期了,我什么也没有。
create_comments.rb
def change
create_table :comments do |t|
t.string :commenter_id
t.text :body
t.references :micropost, index: true, foreign_key: true
t.timestamps null: false
endcomments_controller.rb
def create
micropost = Micropost.find_by(params[:id])
@comment = micropost.comments.build(comment_params)
@comment.commenter_id = current_user.id
@comment.save
redirect_to root_url
end
def destroy
@comment.destroy
flash[:success] = "Comment deleted"
redirect_to request.referrer || root_url
end_comment.html.erb
<% @comment.each do |comment| %>
<p><%= comment.body %></p>
<span class="timestamp">
Posted <%= time_ago_in_words(comment.created_at) %> ago.
<%= link_to "delete", comment, method: :delete %>
</span>
<%end%>_comment_form.html.erb
<%= form_for(Comment.new) do |f| %>
<p>
<%= f.text_area :body, :placeholder => "Leave a comment" %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>routes.rb
resources :microposts
resources :comments _micropost.html.erb
<li id="micropost-<%= micropost.id %>">
<%= link_to micropost.user.name, micropost.user %>
<%= micropost.content %>
<div id="comments">
<%= render "comments/comment" %>
</div>
<%= render 'shared/comment_form' %>
</li>microposts_controller.html.erb
def show
@micropost = Micropost.find(params[:id])
@comment = @micropost.comments(params[:id])
endstatic_pages_controller.html.erb
def home
if logged_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
@comment = Comment.all
end
end发布于 2015-11-30 15:08:47
microposts_controller.html.erb应该是microposts_controller.rb be app/controllers。static_pages_controller.html.erb也是如此。
另外,在MicropostsController#show内部,您不能正确地获得Micropost的注释。你应该有这样的东西:
@comments = @micropost.comments您现在要做的是使用micropost id获得一个特定的注释,这个id很可能返回nil。这就是为什么在destroy上出现错误的原因。
另一个问题可能是,在_micropost.html.erb中,您将您的微博称为micropost,而不是@micropost。
https://stackoverflow.com/questions/34000930
复制相似问题