Ruby Question

optimize code ruby rails

I do this in my edit functions , update, destroy

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

there any way to optimize and make a single function, you used to like this:

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

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

But add the friendly_id gem and modify it as follows:

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

But it gives me error.

Mysql2::Error: Unknown column '' in 'where clause': SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` = 1 AND `id`.`id` = 'primero' LIMIT 1

Answer Source

The find method finds a record by id and you can only pass a single id or an array of ids as input. But in your method, you're passing a hash. Modify your set_user_post method as

def set_user_post
    @post = current_user.posts.friendly.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to root_path, alert: 'You are knocking at the wrong door'

If a user's trying to access another user's post, the find method will raise an exception cause we're finding the posts of the current_user. We can rescue the exception and redirect the user to the home page with a warning flash message.


You can also find a record using find_bymethod and pass it a hash. This method is used to find a record with any field(not just id). It returns the first record which matches the query.

For example,

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

This does the same thing but the difference is that find raises an ActiveRecord::RecordNotFound exception if a record doesn't exist with the given id while find_by returns nil if a record doesn't exist.

For more, see

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download