Search code examples
ruby-on-railsrubyhttp-redirectposts

Ruby on Rails - Couldn't find Post with 'id'=string


Having trouble passing a string as a parameter instead of an ID. I keep getting hit with "Couldn't find Post with 'id'=stack".

routes.rb makes a GET request for a :short_url in the redirect controller.

get '/:short_url' => 'posts#redirect'
resources :posts

post_controller.rb is finding the params[:short_url] of the in the post.

def redirect
    @post = Post.find(params[:short_url])
    redirect_to @post.(params[:url])
end

The view is simply an anchor tag with a @post.each do |post| loop.

    <a class="item" target="_blank" href="<%= post.short_url %">
      <div>Short URL</div>
      <%= post.short_url %>
    </a>

Not sure if I'm calling the parameter at the routes or controller level incorrectly.


Solution

  • The find method finds a record based on the id(which is an integer). If you want to lookup a table based on any other field(in your case, short_url), you need to use the find_by method.

    You're getting the error Couldn't find Post with 'id'=stack as ActiveRecord is looking up the posts table for an id of stack which does not exist. Try

    @post = Post.find_by(short_url: params[:short_url])
    redirect_to @post