【发布时间】:2014-07-14 11:24:55
【问题描述】:
对我来说这很奇怪。
我有 2 个模型(有用户),我有帖子,我有评论。 我想要做的是在 post#show 视图中有 form_for cmets。
但是由于某种原因,当我尝试创建评论时,我得到找不到没有 ID 的帖子。 当我查看请求参数时,虽然我看到:
{"utf8"=>"✓", "authenticity_token"=>"7bAXF66sghTKAF7b61gu08hElC+O1nR6RoT92tqQGOI=", "comment"=>{"content"=>"ok"}, "commit"=>"Add comment", "action"=>"create", "controller"=>"comments", "post_id"=>"23"}
这清楚地表明它确实获得了 post_id 并且在这种情况下它是 23 的 id。
经过无数个小时,我想我会看看你们是否有解决方案。
我的cmets_controller.rb:
class CommentsController < ApplicationController
before_action :load_post
def create
@comment = @post.comments.build(params[:content])
@comment.user = current_user
if @comment.save
@comment.create_activity :create, owner: current_user
redirect_to root_url, notice: "Comment was created."
else
render :new
end
def load_post
@post = Post.find(params[:id])
end
end
我的posts_controller.rb
def show
@post = Post.find(params[:id])
@comment = Comment.new
end
表单cmets/_form.rb
的部分<%= form_for [@post, @comment] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Add comment" %>
<% end %>
我的routes.rb
resources :posts do
resources :comments
end
我的posts/show.html.erb
<%= render @post %>
<h3>New comment</h3>
<%= render 'comments/form' %>
我的posts/_post.html.erb
<h2><%= @post.title %></h2>
<p><%= @post.content %></p>
<em>written by <%= @post.user.fullname %></em>
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4