【问题标题】:Why does Sequel return only the first matching row?为什么 Sequel 只返回第一个匹配的行?
【发布时间】:2017-03-24 07:35:05
【问题描述】:

我有一个名为 sk.db 的 SQLite3 数据库,其中包含一个名为 Sked 的表,该表显示带有日期列的体育比赛日程。下面的代码只给了我第一个匹配的行,而不是所有匹配的行,其中应该有很多。我在where(...) 中使用什么并不重要,它只会给我第一个匹配的行。如果我使用schedule.all,它会给我整个数据库,但如果我使用where,它只会给我第一个匹配的行。

我哪里错了?

.rb

require 'date'
require 'sequel'
require 'sinatra'

DB = Sequel.connect("sqlite://sk.db")

class Sked < Sequel::Model
end

schedule = DB.from(:sked)

get '/' do
  @todaymatches = schedule.where(:date => Date.today)
  erb :games
end

.erb

 <h1>Games</h1>
 <p><%= @todaymatches.inspect %></p>

【问题讨论】:

    标签: ruby sequel


    【解决方案1】:

    .where(...) 查询实际上并不检索记录,它们返回可用于链接更多查询的数据集,例如:

    my_posts = DB[:posts].where(:author => 'david').where(:topic => 'ruby') # no records are retrieved
    

    如果您想实际检索记录,请在末尾添加all

    @todaymatches = schedule.where(:date => Date.today).all # records are retrieved
    

    见:https://sequel.jeremyevans.net/rdoc/classes/Sequel/Dataset.html

    【讨论】:

      【解决方案2】:

      这可能很笨重,但我认为它会做你想做的事。试一试。

      .rb

      .
      .
      .
      get '/' do
        @todaymatches = schedule.where(:date => Date.today)
      
        def print_today_matches
          @todaymatches.each { |x| puts x.inspect }
        end
      
        erb :games
      end
      

      .erb

      <h1>Games</h1>
      <p><%= print_today_matches %></p>
      

      或者,或者:

      .rb

      .
      .
      .
      get '/' do
        @todaymatches = schedule.where(:date => Date.today)
        erb :games
      end
      

      .erb

      <h1>Games</h1>
      <p><%= @todaymatches.each { |x| p x } %></p>
      

      【讨论】:

        猜你喜欢
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多