Search code examples
mysqlrubysinatrasequel

ActiveRecord: retrieve mySQL data based on one field in URL


I have a model called "blog", which has several columns, including one called "token".

I want to retrieve a row based on the token that's in a url - for instance, if the user goes to /blog/post1, I want to retrieve the row where token = post1

In my app setup I'm doing:

get '/blog/:id' do
  @postID = params[:id]
  @thePost = Blog.where(token: @postID)
  render 'blog/index'
end

When I try to access <%= @thePost %> in my .erb file, I get:

#<Sequel::Mysql2::Dataset:0x007fdec1777318>

How do I access the actual data from the row here?


Solution

  • Blog.where(token: @postID) returns a list with all matches - even if the list contains only one elemen. OP is using the Sequel ORM instead of ActiveRecord (Hint is the return type Sequel::Mysql2::Dataset), therefore I would suggest to use first (or first! depending on your usecase) instead of where:

    @thePost = Blog.first(token: @postID)
    

    From the docs:

    An alias for calling first on the model's dataset, but with optimized handling of the single argument case.