“部分” has_many 版本“文章” -- 如何获得最新的子集?
我有一个名为 Section
的模型,其中包含许多文章 (Article
)。这些文章是有版本的(名为 version
的列存储它们的版本号。),我希望检索最新的文章。
从section_id 2检索所有文章的SQL查询是:
SELECT * FROM `articles`
WHERE `section_id`=2
AND `version` IN
(
SELECT MAX(version) FROM `articles`
WHERE `section_id`=2
)
我一直在尝试在Article
模型类中创建一个命名范围,但没有成功,它看起来像这样:
named_scope :last_version,
:conditions => ["version IN
(SELECT MAX(version) FROM ?
WHERE section_id = ?)", table_name, section.id]
用于获取的命名范围无论我需要哪个版本,都可以很好地工作,如下所示:
named_scope :version, lambda {|v| { :conditions => ["version = ?", v] }}
我不想结束使用 find_by_sql
因为我试图尽可能保持所有内容的高水平。任何建议或见解都将受到欢迎。提前致谢!
I have a Model called Section
which has many articles (Article
). These articles are versioned (a column named version
stores their version no.) and I want the freshest to be retrieved.
The SQL query which would retrieve all articles from section_id 2 is:
SELECT * FROM `articles`
WHERE `section_id`=2
AND `version` IN
(
SELECT MAX(version) FROM `articles`
WHERE `section_id`=2
)
I've been trying to make, with no luck, a named scope at the Article
Model class which look this way:
named_scope :last_version,
:conditions => ["version IN
(SELECT MAX(version) FROM ?
WHERE section_id = ?)", table_name, section.id]
A named scope for fetching whichever version I need is working greatly as follows:
named_scope :version, lambda {|v| { :conditions => ["version = ?", v] }}
I wouldn't like to end using find_by_sql
as I'm trying to keep all as high-level as I can. Any suggestion or insight will be welcome. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会看一些版本控制插件,例如 充当版本控制 或 版本 fu 或其他东西。
如果您确实想让它按照现在的方式工作,我会添加一个布尔列来标记它是否是最新版本。运行并为每一列添加该数据并获取最新数据将很容易。您可以通过保存回调轻松使其保持最新。
然后,您可以在文章上添加最新的命名范围,以检查布尔值
,因此对于您可以执行的部分:
更新:
由于您无法向数据库模式添加任何内容,因此我回顾了您在命名范围内的尝试。
然后你应该能够这样做
这不是最干净的,需要将部分扔给 lambda,但我认为没有其他方法,因为直到稍后对象加载时你才可以使用,这就是为什么我认为你的版本失败了。
I would take a look at some plugins for versioning like acts as versioned or version fu or something else.
If you really want to get it working the way you have it now, I would add a boolean column that marks if it is the most current version. It would be easy to run through and add that for each column and get the data current. You could easily keep it up-to-date with saving callbacks.
Then you can add a named scope for latest on the Articles that checks the boolean
So for a section you can do:
Update:
Since you can't add anything to the db schema, I looked back at your attempt at the named scope.
You should be able to then do
It isn't the cleanest with that need to throw the section to the lambda, but I don't think there is another way since you don't have much available to you until later in the object loading, which is why I think your version was failing.