在 rails "couldn't find error" 中使用表单参数查找记录

Find a record using form params in rails "couldn't find error"

我是 rails 的新手。我正在尝试使用在表单字段中提交的值来查找 'Category' 记录。因为我一直使用 Find by params[:id] 来查找 url 参数,所以我认为它适用于表单参数。

这是我的错误

Couldn't find Category with 'id'=

on this line:

 @category = Category.find(params[:category_id])

这是我的代码

posts_controller.rb

def delete
  @post = Post.find(params[:id])
  @category = Category.find(@post.category_id)
  @post_archive = PostArchive.new
end

def destroy
 @post = Post.find(params[:id])
 *@category = Category.find(params[:category_id])* <--the error hits here
 @old_id = params[:post_id]
 @author_id = params[:author_id]
 @followers = Follower.find(post_id: @old_id)
 @post_archive = PostArchive.new

 PostArchive.create!(post_id: @old_id, author_id:   @author_id , removed_by: current_user.id,
  category_id: @category.id, 
  post_created_at: @post.created_at )
 @post.destroy

 @followers.each do |follower|
       ProjectMailer.post_deletion(current_user, @category, @author_id, follower, @old_id ).deliver
  end
  @followers.destroy_all
  redirect_to posts_path, notice: 'Project Deleted' 
end

表格

<%= form_for :delete_post, url: post_destroy_path(@post), method: :delete do |f| %>
<%= f.hidden_field :author_id@post.author_id %>
<%= f.hidden_field :category_id, @post.category_id  %>
<%= f.hidden_field :post_id, value: @post.id %>
Are you sure you want to delete <%=@post.title %>?
<%=f.submit %>
<% end %>


我已经测试过我可以使用 Categorgy.find(2) 找到参数并且我已经测试过该参数实际上显示在表单中(它是一个隐藏字段......所以我需要)


服务器日志:

Processing by PostsController#destroy as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"s2pglEj+LUIvZ8OJ0i/sbb3T8hDTcFrqdV0rJqa3c/pihtrMez4S5A8bK3NmoQ/BleKrMRuMTUhZvCwl+00jeQ==", "delete_post"=>{"author_id"=>"21", "category_id"=>"2", "post_id"=>"417"}, "commit"=>"Delete Post", "id"=>"417"}
def destroy
 @post = Post.find(params[:id])
 *@category = Category.find(params[:category_id])* <--the error hits here
 # change to 
 # *@category = Category.find(params[:delete_post][:category_id])*     
 @old_id = params[:post_id]
 @author_id = params[:author_id]
 @followers = Follower.find(post_id: @old_id)
 @post_archive = PostArchive.new

 PostArchive.create!(post_id: @old_id, author_id:   @author_id , removed_by: current_user.id,
  category_id: @category.id, 
  post_created_at: @post.created_at )
 @post.destroy

 @followers.each do |follower|
       ProjectMailer.post_deletion(current_user, @category, @author_id, follower, @old_id ).deliver
  end
  @followers.destroy_all
  redirect_to posts_path, notice: 'Project Deleted' 
end

从你的参数可以看出,category_iddelete_post

里面
Parameters: {"delete_post"=>{"author_id"=>"21", "category_id"=>"2", "post_id"=>"417"}, "commit"=>"Delete Post", "id"=>"417"}

应该是

@category = Category.find(params[:delete_post][:category_id])