如何更新模型的"的updated_at"只为列更新的一个子集领域? [英] How to update a model's "updated_at" field only for a subset of column updates?

查看:244
本文介绍了如何更新模型的"的updated_at"只为列更新的一个子集领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个典型的博客应用程序。每个用户的has_many帖子。每一个职位的has_many标签。 我在整理各岗位通过的updated_at所以最近更新的帖子会出现在上面。因此,举例来说,如果我更新后的内容,后上来了顶端。然而,这也发生在我只需添加一个标签,因为标签连接到其相应的职务。

There is a typical blog application. Each user has_many posts. Each post has_many tags. I'm sorting each post by updated_at so the most recently updated post will show up on top. So for example, if I update a post's content, the post will come up to the top. However, this also happens when I just add a tag, since a tag is connected to its corresponding post.

我只想内容更新改变的updated_at领域。我不想要的updated_at的岗位,因为我加了一个标签进行更改。有没有办法做到这一点?还是有其他的方式来实现这样的事情?谢谢!

I only want the content update to change updated_at field. I don't want updated_at for a post to be changed because I added a tag. Is there a way to do this? Or any other way to achieve something like this? Thank you!

推荐答案

两种方法涌现在脑海:

  1. 不要使用:的updated_at 为您正在使用它的目的。相反,创建新列,说:post_updated_at ,并在每个手动更新保存要引起后移动到顶部。 Rails提供一个方便的模式mehod此:

  1. Don't use :updated_at for the purpose you are using it for. Instead create a new column, say :post_updated_at, and update it manually on each save that you want to cause the post to move to the top. Rails provides a convenient model mehod for this:

mypost.touch :post_updated_at

  • 当您正在更新列,并希望:的updated_at 来保持不变,使用的 #update_column 方法,它直接更新列在数据库中你给它的价值。请注意,它是将值写入数据库逐字,所以你必须要聪明,如果有问题的列是看中连载列或相似的。

  • When you are updating a column and want :updated_at to remain untouched, use the #update_column method, which directly updates the column in the database with the value you give it. Note that it writes the value to the database verbatim, so you will have to be clever if the column in question is a fancy serialize column or similar.

    这篇关于如何更新模型的"的updated_at"只为列更新的一个子集领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆