【问题标题】:How to return true if string exists in table, Ruby on Rails如果表中存在字符串,Ruby on Rails如何返回true
【发布时间】:2017-10-05 05:12:18
【问题描述】:

我需要控制器检查表中是否存在字符串,然后返回“true”或“false”,以便我可以在 if 语句中使用它。 例如,如果“my_friends”表中存在字符串“Robert”,我需要从另一个名为“goodtimes”的表中显示与“Robert”相关的那些对应项。

我意识到 .exists 在此应用程序中不起作用,因为我正在搜索字符串。

@my_friends.where(friend_id: 'Robert').exists?   #always returns false
    @goodtimes = goodtime.where friend_id: "Robert" #works

伪代码如下所示:

if (table x contains string "Robert")
    @goodtimes = goodtime.where friend_id: "Robert" #display goodtimes from table y

提前致谢, 戴夫

【问题讨论】:

  • 您想在表格的每一列中搜索该字符串?
  • 不,只是friend_id 列。两个表中都有friend_id 列。
  • 使用你的模型,做一个常规的AR查询,你要查询的表的模型是什么?
  • 我应该说我是 Rails 新手。我不明白你的问题。模型目录中的文件不包含类以外的任何内容,然后结束。什么是 AR 查询?顺便说一句,感谢您的帮助。
  • 你能发布你正在使用的完整代码块吗?

标签: ruby-on-rails string


【解决方案1】:

您可以使用.where().present检查罗伯特是否存在

if @my_friends.where(:friend_id => 'Robert').present?
  # Robert exists
else
  # Robert doesn't exist
end

查看this answer了解更多检查记录是否存在的方法。

【讨论】:

  • 谢谢香巴拉巴拉!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2022-12-10
相关资源
最近更新 更多