【发布时间】:2016-09-04 09:22:01
【问题描述】:
假设我有一个带有 2 组复选框的网页表单用户界面。使用第 1 组复选框,我可以勾选我想要的训练师(“Jason”、“Alexandra 等)。使用第 2 组复选框,我可以勾选我想要看到的动物(“老虎”、“熊”、等等)一旦我提交了带有这些选项的表格,我会返回一个符合标准的动物园列表(假设所有的培训师都在所有的动物园工作,所有的动物都在所有的动物园里,以便讨论)
我们将通过“名称”运行我们的数据库查询(例如,使用训练师名称和动物名称进行搜索,而不是数据库 ID)
假设我们正在使用具有数十万行(如果不是数百万行)的 Postgres 数据库。
- 使用“ILIKE”查询搜索效率更高还是使用标准连接查询更好(例如,
Zoo.includes(:animals, :trainers).where("animals.name = ? and trainers.name = ?", animal_names, trainer_names)? - 有没有比我刚才在上面 #1 中展示的更好的方法?
模型设置
class Zoo < ActiveRecord::Base
has_many :animals, through: zoo_animals
has_many :trainers, through: zoo_trainers
has_many :zoo_trainers
has_many :zoo_animals
end
class Animal < ActiveRecord::Base
has_many :zoos, through :zoo_animals
has_many :zoo_animals
end
class Trainer < ActiveRecord::Base
has_many :zoos, through :zoo_trainers
has_many :zoo_trainers
end
class ZooAnimal < ActiveRecord::Base
belongs_to :animal
belongs_to :zoo
end
class ZooTrainer < ActiveRecord::Base
belongs_to :zoo
belongs_to :trainer
end
编辑:假设我无权访问数据库 ID。
【问题讨论】:
-
为什么不从表单中返回 ID?
-
好点,假设我也可以这样做。
-
但我仍然想回答这个问题 - 假设我无权访问数据库 ID。
-
您需要什么
LIKE或ILIKE查询?您是要搜索“%Jason%”还是“Jason%”还是只搜索“Jason”或其他内容? -
Both - 基本上是任何包含子字符串“Jason”的选项
标签: ruby-on-rails ruby postgresql rails-activerecord