Error searching for records by id with friendly_id

5

I do this in my functions edit, update, destroy

@post = Post.friendly.find(params[:id])
if @post.user_id == current_user.id

There is some way to optimize and make a single function, before doing it this way:

before_action :set_user_post, only: [:edit, :update, :destroy]

private
def set_user_post
  @post = current_user.posts.find_by(id: params[:id])
end

But add the friendly_id gem and modify it like this:

private
def set_user_post
  @post = current_user.posts.friendly.find(id: params[:id])
end

But I get an error.

    
asked by Carlos Uriel Patiño Santiago 13.08.2016 в 20:45
source

2 answers

1

Solution

begin
    @post = current_user.posts.friendly.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to @post
  end
    
answered by 17.08.2016 / 23:22
source
3

The error is generated because you are using find(id: params[:id]) when it should be find(params[:id]) .

    
answered by 16.08.2016 в 00:15