Activerecord解决postgres-mysql问题
我的作业模型中有以下范围,并且我的语句中的一些 SQL 差异似乎存在问题。我们的开发数据库是mysql,显然heroku有postgres,并且由于某种原因它一直抱怨file_count。
我计划将这些范围转换为类方法,或者至少将 SQL 语句更改为活动记录语句,这样它就可以独立于数据库。这有可能吗?我该如何开始呢?
我计划保留 is_active 因为我很确定它可以工作,因为它是一个简单的范围声明,但是 with_unclassified_files_available_count 需要重构,我认为 AR 重构将是一个好主意(如果你认为这不是一个好主意,请告诉我,我愿意接受建议)
这是代码:
scope :is_active, where(:active => true)
scope :with_unclassified_files_available_count, where("audio_files.category_id IS NULL")
.joins(AUDIO_FILES)
.select("jobs.*, COUNT(*) AS file_count")
.group("jobs.id")
.order("batch_identifier DESC")
scope :has_files_available, with_unclassified_files_available_count.having("count(*) > 0")
scope :available_to_work_on, is_active.has_files_available
附加信息:
作业有许多audio_files并且AudioFile属于作业。
I have the following scopes in my Job model and it seems there's a problem with some SQL discrepancies in my statements. Our dev db was mysql and apparently heroku has postgres and it keeps complaining about as file_count for some reason.
I plan to just convert these scopes into class methods or at least change the SQL statements into active record ones so it could be db independent. Is this possible at all and how would I start on this one?
I'm planning to keep is_active because I'm pretty sure it works as it's a simple scope statement, but with_unclassified_files_available_count needs a refactor and I think an AR refactor would be a good idea(if you think this isn't a good idea, please tell me so, I'm open to suggestions)
Here's the code:
scope :is_active, where(:active => true)
scope :with_unclassified_files_available_count, where("audio_files.category_id IS NULL")
.joins(AUDIO_FILES)
.select("jobs.*, COUNT(*) AS file_count")
.group("jobs.id")
.order("batch_identifier DESC")
scope :has_files_available, with_unclassified_files_available_count.having("count(*) > 0")
scope :available_to_work_on, is_active.has_files_available
Additional info:
Job has many audio_files and AudioFile belongs to job.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了 MySQL 之外,没有任何数据库会接受这种构造。您在 SELECT 部分中提到的不在聚合函数中的每一列(如 COUNT、MIN、MAX)必须位于 GROUP BY 中。 GROUP BY 中只有 jobs.id。
您必须更改查询并提及 GROUP BY 中的所有列。
MySQL 的这种构造也存在问题,在许多情况下它会产生奇怪/错误的结果。 MySQL 已经实现了 SQL 模式 ONLY_FULL_GROUP_BY 要关闭此行为,MySQL 现在也会拒绝这样的查询。
诗。 不要在查询中使用 *,没有人知道结果是什么可能是。
No database, except MySQL, will accept this construction. Every column you mention in the SELECT section that is not in an aggregate function (like COUNT, MIN, MAX) MUST be in the GROUP BY. You only have jobs.id in the GROUP BY.
You have to change your query and mention all columns in the GROUP BY.
MySQL also has problems with this construction, in many cases it produces strange/wrong results. MySQL has implemented the SQL-mode ONLY_FULL_GROUP_BY to turn off this behaviour, MySQL will now also reject queries like this.
Ps. Don't use * in your queries, nobody has any idea what the results might be.