我有用戶/微博/評論模型,用戶可以在其中評論他人的微博。在每個帖子下面顯示一個文本框,以便用戶可以輸入評論,但是我很努力地找到Micropost ID。我認爲問題出在我的form_for評論或控制器上,但我不確定。會喜歡一些幫助,謝謝。如何將評論表單與正確的帖子相關聯
錯誤:沒有ID無法找到微柱
型號:
User Model: has many microposts, has many comments
Micropost Model: belongs to user, has many comments
Comment Model: belongs to micropost, belongs to user
用戶控制器:
def show #(the profile page where all the posts and comments are)
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
@micropost = current_user.microposts.build if signed_in?
@comments = @micropost.comments
@comment = current_user.comments.build(:micropost => @micropost) if signed_in?
end
評論控制器:
def create
@micropost = Micropost.find(params[:id])
@comment = current_user.comments.build(:micropost => @micropost) #can someone explain what happens in the parentheses?
@comment.user = current_user
@comment.save
redirect_to :back
end
查看/評論/_評論_形式:
<%= form_for(@comment) do |f| %>
<div id="comment_field">
<%= f.text_field :content, placeholder: "Say Something..." %>
</div>
<% end %>
路線:
resources :users
resources :microposts, only: [:create, :destroy]
resources :comments, only: [:create, :destroy]
我仍然得到相同的錯誤沒有發現micropost id指向評論控制器創建方法 – Jaqx
我調整了我的答案根據您當前的控制器代碼:) – jvnill
我遇到的問題是,在評論控制器Micropost查找params id返回爲零。我不知道如何瞄準正確的職位。當我在form_for中聲明micropost的值爲4時,它會在db中插入註釋但是我必須將控制器中的@comment更改爲= current_user.comments.build(params [:comment]) – Jaqx