ActiveRecord find ignores extra characters after numeric id. ?

Doesn’t work for me in rails 6

Parameters: {“id”=>“18-test-title”}
ActionController::ActionControllerError (Cannot redirect to nil!):

Ne

From the docs: https://apidock.com/rails/v6.0.0/ActiveRecord/FinderMethods/find

[Person](https://apidock.com/rails/Person).[find](https://apidock.com/rails/ActiveRecord/FinderMethods/find)("31-sarah") # returns the object for ID = 31

In your case, if you are using find, it should search for record with id = 18

I’ve over-riding ActiveRecord to_param in my model

def to_param
“#{id}-#{title.parameterize}”
end

find method doesn’t care about the to_param method, it just takes the parameter you use, I guess it calls “to_i” and uses that integer to query the id column

Why don’t you show your code, the stacktrace, the logs or anything? I suggest you read something like stackoverflow’s guidelines on how to ask, you posts are usually really hard to understand and a lot of information is missing

I was trying to implement this guide:

https://medium.com/badass-engineer/seo-friendly-urls-with-rails-49cfcd2fb190

I insist, show your code, show the complete error stacktrace, show the log. I can imagine what you are trying to do and from the (little) code you show it should work so something else is messing things up but you are showing barely any relevant code.

The error’s caused by the routine ensure_canonical_url If I comment it out it works

blog_post.rb:

def to_param
“#{id}-#{title.parameterize}”
end

blog_posts_controller.rb:

def set_blog_post
@blog_post = BlogPost.find(params[:id])
end

def ensure_canonical_url
redirect_to @blog_post if @blog_post.to_param != params[:id]
end

So what do you think is wrong with ensure_canonical_url ?

I guess you are calling ensure_canonical_url before_action BEFORE set_blog_post before_action, so it’s not already set.

I guess you have something like:

before_action :ensure_canonical_url, only: :show
before_action :set_blog_post, only: :show

swap both lines if so.