ruby-on-rails - Rails 从简单模型中提取数据的最有效方法
问题描述
我有两个简单的模型——我必须Campaign
从中CampaignCode
提取一些已经使用过的模型CampaignCode
。因为它是大量数据(仅一个活动的 200k 代码)我想知道哪种方式最有效?
query
CampaignCode.where(state: 'used').count
我认为query
这只能用少量数据解决问题,我应该使用include
还是一些连接表?
campaign
模型
# created_at :datetime not null
# end_date :date
# id :bigint(8) not null, primary key
# name :text not null
# start_date :date
# updated_at :datetime not null
class Campaign < ApplicationRecord
has_many :campaign_codes
validates :name, presence: true
end
campaign_code
模型
#created_at :datetime not null
#campaign_id :bigint(8)
#state :integer
#uid :string not null, primary key
#updated_at :datetime not null
class CampaignCode < ApplicationRecord
self.primary_key = :uid
belongs_to :campaign
validates :uid, uniqueness: true
end
解决方案
如果您需要速度,您必须使用直接 SQL 并使用数据库的技巧。
我会在您的模型中进行自定义查询(如果是 PostgreSQL):
def self.count_used_codes
sql = <<-SQL
SELECT count(*) FROM campaign_codes WHERE state == 'used';
SQL
self.find_by_sql(sql)
end
然后使用
CampaignCode.count_used_codes
然后,您还可以根据您的具体使用情况给自己一些优化的灵活性。如果您不担心准确性,您还可以尝试估计的计数,这可能会更快,但这些东西有点超出我的知识范围。
我还看到人们在应用程序中创建一个特定的 sql 文件夹,然后在其中引用复杂的查询以保持它的干净。
推荐阅读
- python - Flask 应用程序 ImportError:尝试在没有已知父包的情况下进行相对导入
- python - 如何在 Python 中有效地遍历选定的 Excel 工作表并将它们附加到数据框中?
- python - I am unable to edit my shortcuts on Jupyter Notebook?
- reactjs - Facebook 错误:此端点需要“manage_pages”或“pages_read_engagement”权限
- android - AOSP Android.bp 中预构建的 libtensorflowlite.so 库,构建失败,权限被拒绝
- angular - 从 9 到 10 的 PrimeNG 更新失去了我的风格
- javascript - 如何在javascript中获得相当于encryptJs的java
- python - Python ElementTree 命名空间注册了两个“空前缀”命名空间
- python - 使用python删除json文件中的Z坐标
- javascript - javascript {name:“demo1”,franchise_id:null,number:“98765”,status:“good”}如何获取值期望空键值