【问题标题】:How can I get this ruby code with sequel to work in sinatra?我怎样才能让这个 ruby​​ 代码和续集在 sinatra 中工作?
【发布时间】:2015-12-01 05:08:23
【问题描述】:

我试图只允许一个人在他们的名字在数据库中查看该页面。我认为最好的方法是遍历所有条目并检查它是否匹配,如果匹配则显示并停止循环。我总是得到一个空白页,有什么帮助吗?

get '/' do
  user  = "john"
  num = DB[:users].all

  for person in num  do
    if person[:name].to_s == user then
      File.read('index.html')
      break
    else 
      "you're not authorized"
    end
  end

end

如果我要删除 if 语句中的 break 行,我会收到以下错误:

  NoMethodError at /
  undefined method `bytesize' for #<Hash:0x007fcf60970a68>
  file: utils.rb location: bytesize line: 369

【问题讨论】:

  • 您忘记发布您遇到的错误。
  • 我得到的是一个空白页面,我在尝试其他类似的事情时遇到了错误,但具体来说,我的页面是空白的,我不知道为什么,如果我拿出'break' 我得到下面的错误

标签: ruby sinatra sequel


【解决方案1】:

问题在于 for 循环的计算结果为 nil(除非您 break 并向 break 提供值),因此您的块返回 nil,因此没有要渲染的内容。

但真正的问题是 for 在这里是错误的解决方案。您要做的是检查数组DB[:users].all 是否包含其:name 成员等于user 的哈希。您可以为此使用循环,但除了 for 在惯用的 Ruby 代码中很少见(Enumerable#each 是首选)之外,它会使您的代码的意图更难理解。相反,您可以像这样使用Enumerable#find(Array 类包括 Enumerable 模块中的方法):

get '/' do
  username = "john"
  users = DB[:users].all

  matching_user = users.find do |user|
    user[:name] == user
  end

  if matching_user
    return File.read('index.html')
  end

  "you're not authorized"
end

...但是由于您实际上并不关心匹配用户——您只关心匹配用户是否存在@或false

get '/' do
  username = "john"
  users = DB[:users].all

  if users.any? {|user| user[:name] == user }
    return File.read('index.html')
  end

  "you're not authorized"
end

编辑:正如@user846250 指出的那样,最好让数据库来检查是否存在任何匹配的用户。像这样的:

get '/' do
  username = "john"

  if DB[:users].where(:name => username).empty?
    return "you're not authorized"
  end

  File.read('index.html')
end

这是更可取的,因为不是将数据库中的所有记录加载到 Ruby 中(DB[:users].all 会这样做)——当你实际上并不关心它们中的任何数据时——Sequel 只会询问数据库如果有匹配的记录,则返回truefalse

【讨论】:

  • 哇,谢谢,我不知道在 ruby​​ 中很少见,我只是来自基本的 python。
  • 而且由于您使用的是Sequel,因此您实际上可以使用更类似于SQL 的查询,例如!DB[:users].where(:name =&gt; username).empty?,如果用户存在则返回true,否则返回false。跨度>
  • 很好,@user846250。我已经编辑了我的答案以包含这些方面的信息。
猜你喜欢
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多