【问题标题】:Rails 4: Model union with itselfRails 4:与自身的模型联合
【发布时间】:2014-03-26 21:30:47
【问题描述】:

我是 Rails 新手,请见谅。 我有一个现有的数据库架构

create_table "registrations", force: true do |t|
   t.string   "name",                                   null: false
   t.string   "product1",                               null: false
   t.string   "product_serial1",                        null: false
   t.string   "product2",                               null: false
   t.string   "product_serial2",                        null: false
   t.string   "product3",                               null: false
   t.string   "product_serial3",                        null: false
   t.string   "product4",                               null: false
   t.string   "product_serial4",                        null: false
end

在 UI 上,我希望能够搜索序列号,它需要搜索 product1、product2、product3...

我的想法是让模型联合起来,这样所有的产品都会在自己的行中返回,就像

select name, product1 product, serial1 serial from registrations where product1 != ''
union all
select name, product2 product, serial2 serial from registrations where product2 != ''
union all
select name, product3 product, serial3 serial from registrations where product3 != ''
union all
select name, product4 product, serial4 serial from registrations where product4 != ''

Rails 可以在模型中做这样的事情吗?就像控制器一样,如果我注册.search(),它会默认返回上面的 SQL。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model


    【解决方案1】:

    我认为您正在寻找类似于以下内容的内容

    Registration.where("product_serial1 = ? OR product_serial2 = ? OR product_serial3 = ? OR product_serial4 = ?", search_string, search_string, search_string, search_string)
    

    附带说明一下,您可能真的想再看看您的架构。这些产品序列号看起来像是属于产品表,您的注册表应该通过中间表连接到许多产品。这个article 可能会有所帮助。

    【讨论】:

    • 这是我目前拥有的,但正在寻找更好的解决方案。上面的问题是,如果用户有两个产品和一个序列匹配项,在视图中我同时显示 product1 和 product2,因为结果集就是这样。理想情况下,我只会返回与一种产品匹配的一种结果。我在想也许我需要调整数据库。我希望不要因为这是一个现有的数据库。
    【解决方案2】:

    这可能会有所帮助:

    Registration.where("product_serial1 like :search or product_serial2 like :search or product_serial3 like :search or product_serial4 like :search", search: "#{params[:search]}")
    

    这将搜索所有的序列字段并且只返回匹配的记录。请注意,此示例使用 params[:search],但这可以替换为变量。

    【讨论】:

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