[英]Comments to Microposts: Create and Delete Comments in Rails ?
當我嘗試刪除注釋時,出現錯誤“ nil:NilClass的未定義方法`destroy'”
當我向不同的微博添加評論時;所有評論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
end
comments_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])
end
static_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
microposts_controller.html.erb
應該是app/controllers
microposts_controller.rb
。 相同於static_pages_controller.html.erb
。
另外,在MicropostsController#show
內部,您沒有正確收到Micropost
的注釋。 您應該具有以下內容:
@comments = @micropost.comments
您現在正在做的是嘗試使用微博ID獲得特定評論,該ID很可能返回nil
。 這就是為什么您會得到destroy
的錯誤的原因。
另一個問題可能是在_micropost.html.erb
您將微_micropost.html.erb
稱為micropost
@micropost
,而不是@micropost
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.