【问题标题】:Can we set the name of db table as variable in queries in Ruby using SQLite3?我们可以在使用 SQLite3 的 Ruby 查询中将 db 表的名称设置为变量吗?
【发布时间】:2015-06-19 06:30:05
【问题描述】:

我是 Ruby on Rails 的新手,如果我的问题太明显,请原谅我。 根据我对数据库的了解,我无法执行以下操作,但我最近没有在这个领域工作。

我想做的是:

我有一个名为“Patients”的表,其中包含字段、疾病和城市。

我想实现以下查询:

Patient.select(city:"Paris")

我可以将表名设置为这个select语句的变量吗?

谢谢

【问题讨论】:

  • 您的意思是要从“巴黎”城市中选择所有患者?在这种情况下,您需要: Patient.where(city: "Paris")
  • 不,我的意思是我想将患者设置为变量.. 这可能吗?引用表的名称
  • 这可能吗? var = Patient 然后 var.select(city: "Paris")
  • 您想将多个查询链接在一起还是将关系传递给一个方法?如果是这样,您可以使用 var = Patient.scoped。也许你应该解释一下你想要达到的目标?
  • 你发现了吗?

标签: mysql ruby-on-rails ruby sqlite


【解决方案1】:

你可以这样做

table_name = "Patient"
table_name.constantize.select(city:"Paris")

【讨论】:

    【解决方案2】:

    eval 也可以在这里使用:

    > object_type = "Patient"
    > query = "#{object_type}.select(city:'Paris')"
    > eval(query)
    

    【讨论】:

      【解决方案3】:

      我认为基于您想要传递关系对象的 cmets。您可以使用作用域方法来做到这一点。 Ryan Bates 对使用它们有很好的了解:http://railscasts.com/episodes/112-anonymous-scopes

      在你的情况下,你会这样做:

      scope = Patient.scoped
      scope = scope.where(city: "Paris")
      # ... other query options perhaps..eg
      scope = scope.where(name: "John")
      scope = scope.limit(10)
      scope.all # => first 10 Patients from Paris named John
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2021-12-14
        • 2021-04-08
        • 2012-09-06
        • 1970-01-01
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多