I do this in my edit functions , update, destroy
@post = Post.friendly.find(params[:id])
if @post.user_id == current_user.id
before_action :set_user_post, only: [:edit, :update, :destroy]
@post = current_user.posts.find_by(id: params[:id])
@post = current_user.posts.friendly.find(id: params[:id])
Mysql2::Error: Unknown column 'id.id' in 'where clause': SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` = 1 AND `id`.`id` = 'primero' LIMIT 1
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 begin @post = current_user.posts.friendly.find(params[:id]) rescue ActiveRecord::RecordNotFound redirect_to root_path, alert: 'You are knocking at the wrong door' end end
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.
def set_user_post @post = current_user.posts.friendly.find_by(id: params[:id]) end
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
nil if a record doesn't exist.
For more, see http://apidock.com/rails/ActiveRecord/FinderMethods/find