Search code examples
ruby-on-railsformsruby-on-rails-4destroy

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


I am new to rails. I am trying to Find a 'Category' record using a value submitted in a form field. Since I use Find by params[:id] for url parameters all the time, I thought it would work for form parameters.

This is my error

Couldn't find Category with 'id'=

on this line:

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

Here is my code

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

<%= 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 %>


I've tested that I can find the param using Categorgy.find(2) and I've tested that the param is actually showing up in the form (it's a hidden field....so I needed to )


server log:

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"}

Solution

  • As you can see from your params, category_id is inside delete_post

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

    It should be

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