我有用户/微博/评论模型,用户可以在其中评论他人的微博。在每个帖子下面显示一个文本框,以便用户可以输入评论,但是我很努力地找到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