我有用户/微博/评论模型,用户可以在其中评论别人的微博。在每个帖子下面都会显示一个文本字段,这样用户就可以输入评论,但是我很难找到微博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]发布于 2013-02-05 20:56:30
只需为micropost_id添加一个隐藏字段
<%= form_for(@comment) do |f| %>
<%= f.hidden_field :micropost_id, value: @micropost.id %>
<div id="comment_field">
<%= f.text_field :content, placeholder: "Say Something..." %>
</div>
<% end %>更新:传递micropost_id而不对控制器进行任何更改
根据您的comments控制器,您会发现在提交表单时缺少基于params[:id]的micropost。下面的代码解决了这个问题。但是,我建议您查看嵌套资源,这将使控制器代码更美观、更流畅。
<%= form_for @comment do |f| %>
<%= hidden_field_tag :id, @micropost.id %>
<div id="comment_field">
<%= f.text_field :content, placeholder: "Say Something..." %>
</div>
<% end %>或更新表单的action
<%= form_for @comment, url: comments_path(id: @micropost.id) do |f| %>
<div id="comment_field">
<%= f.text_field :content, placeholder: "Say Something..." %>
</div>
<% end %>更新:对注释控制器进行编辑
# view
<%= form_for @comment do |f| %>
<%= hidden_field_tag :micropost_id, @micropost.id %>
<div id="comment_field">
<%= f.text_field :content, placeholder: "Say Something..." %>
</div>
<% end %>
# comments_controller.rb
def create
@micropost = Micropost.find params[:micropost_id]
@comment = current_user.comments.build
@comment.micropost = @micropost
@comment.save
end发布于 2013-02-05 21:08:06
你应该这样设置你的评论资源:
resources :users
resources :microposts, only: [:create, :destroy] do
resources :comments, only: [:create, :destroy]
end以上资源称为嵌套资源。在你的例子中,评论总是与微博相关,你应该将评论资源嵌套到microposts和评论控制器中:
def create
@micropost = Micropost.find(params[:id])
@comment = current_user.comments.build(:micropost => @micropost) #can someone explain what happens in the parentheses?
@comment.save
redirect_to :back
end上面的构建方法创建了一个新的注释模型的对象/实例,因为您已经使用了current_user.comments,这意味着该对象将自动拥有user_id = current_user.id,您不需要再次指定它。和'build(:micropost => @micropost)‘会将micropost's id添加到@comment对象。
https://stackoverflow.com/questions/14707907
复制相似问题