如何“触摸”仅当满足某些条件时才创建“belongs_to”关联的父模型?
我正在使用 Rails 3.1.0,并且仅当满足某些条件时,我才想“触摸”belongs_to 关联的父模型。
例如,此时我有:
belongs_to :article,
:touch => true
只有当父模型是“公共”时,我才会“触摸”它。也就是说,Article
类有一个名为 access
的属性(@article.access
=> public
或 < code>private),我想在“触摸”之前检查这个值:如果这个值不是 public
,那么“触摸”它!
是否可以在 belongs_to
关联语句中“直接”实现这一点?如果是这样,怎么办?
I am using Rails 3.1.0 and I would like to "touch" a parent model of a belongs_to
association only if certain conditions are met.
For example, at this time I have:
belongs_to :article,
:touch => true
I would "touch" the parent model only if it is "public". That is, the Article
class has an attribute named access
(@article.access
=> public
or private
) and I would like to check this value before "touching": if this value is not public
, then "touch" it!
Is it possible to make that "directly" in the belongs_to
association statement? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以像你说的那样尝试 lambda 但我不确定它是否会起作用。像这样的事情:
根据实现也许你可以尝试返回
nil 而不是
false
如果这不起作用,请使用保存前回调,如下所示:
如果您有任何问题,请告诉我。
更新 #1
来自
add_touch_callbacks
的相关部分:因此,如果您传递 true,则对
updated_at
属性进行简单的触摸。如果您传递字段名称,则更新该字段,除非您传递nil
。如果你传递 nil 则不会更新任何内容。这就是为什么我说也许你可以尝试第二个版本的belongs_to
关联。You can try lambda as you said but I'm not sure if its going to work. Something like this:
According to the implementation maybe you can try to return
nil
instead offalse
in the proc, when it's not availableIf this doesn't works use a before save callback like this:
Let me know if you have any questions.
Update #1
The relevant part from
add_touch_callbacks
:So if you pass true, then does a simple touch on
updated_at
attribute. If you pass a field name then updates that field unless you passnil
. If you pass nil doesn't updates nothing. That's why I said that maybe you can try the second version ofbelongs_to
association.我认为您不能将触摸应用到belongs_to 关联中的条件。
有一种方法有点hacky,但可以直接与belongs_to关联一起工作,
这可能不是推荐的方法
I don't think you can apply touch with a condition in a belongs_to association.
There is a way which is a bit hacky but will work directly with a belongs_to association,
This may not be the recommended way