當我試圖刪除評論,我有一個錯誤,「未定義的方法'破壞」的零:NilClass」對Microposts的評論:在Rails中創建和刪除評論?
當我添加註釋,以不同的微觀柱;所有評論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'也一樣。 – linkyndy
是的,你是對的。當我問了問題時,我寫錯了:) – Takor