【问题标题】:Couldn't find Post without an ID even though request parameters says I do即使请求参数说我也找不到没有 ID 的帖子
【发布时间】: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


    【解决方案1】:

    您收到的"post_id" 不是"id"

    出于安全考虑,您可以将 load_post 操作设为私有

    private
    
     def load_post
      @post = Post.find(params[:post_id])
     end
    

    访问content 喜欢

    def create
     @comment = @post.comments.build(params[:comment][:content]) 
    ....
    

    【讨论】:

    • 太好了,这似乎有效,但导致另一个错误,它似乎没有保存:内容。但是它确实保存了 id、user_id 和 post_id。有什么想法吗?
    • 如果这有帮助,您可以勾选答案,对于您的问题,请检查我已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多