ActiveRecord:根据 URL 中的一个字段检索 mySQL 数据

ActiveRecord: retrieve mySQL data based on one field in URL

我有一个名为 "blog" 的模型,它有多个列,包括一个名为 "token" 的列。

我想根据 url 中的标记检索行 - 例如,如果用户转到 /blog/post1,我想检索 token = post1 所在的行

在我的应用程序设置中,我正在做:

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

当我尝试访问我的 .erb 文件中的 <%= @thePost %> 时,我得到:

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

如何从此处的行访问实际数据?

您正在 return 建立关系,您想要 return 的是实际记录。为此,请在 where 调用结束时使用 first

Blog.where(token: @postID).first

Blog.where(token: @postID) returns 包含所有匹配项的列表 - 即使该列表仅包含一个元素。 OP 使用 Sequel ORM 而不是 ActiveRecord(提示是 return 类型 Sequel::Mysql2::Dataset),因此我建议使用 first(或 first! 取决于你的用例)而不是 where:

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

来自文档:

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