Rails - 试图翻转儿童协会中的活跃旗帜
我有两个模型,论坛和主题,论坛有很多主题。每个都有一个活跃的布尔值。当我翻转论坛上的活动标志时,我希望它的主题也都翻转其标志。我的想法是在 before_save 中执行此操作 def before_save 除非自我主动? self.topics.each{|主题|主题.关闭} 在主题
中,我定义了 close 方法: 确定关闭 自我主动=假 自救 我在这里是否
采取了错误的方法(我应该在其他地方做,比如在控制器中?)我没有收到任何错误,但是当我将标志设置为 false 时什么也没有发生(我不一定想翻转所有将论坛设置为活动状态时要活动的主题的数量,因此我只需要这样做)。
谢谢
I have two models, Forums and Topics, Forums has many Topics. Each has an active boolean. When I flip the active flag on a Forum, I want its Topics to all get their flag flipped as well. My thought was to do this in a before_save
def before_save
unless self.active?
self.topics.each{|topic| topic.close}
end
In Topic, I have defined the close method:
def close
self.active = false
self.save
end
Am I taking the wrong approach here (should I be doing is elsewhere, like in a controller?) I don't get any errors, but nothing happens when I set the flag to false (I don't necessarily want to flip all of the topics to active when setting the forum to active, so I only need this to go one way).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,你的方法是正确的,你只需要轻轻推动即可。请参阅下面的示例。
您还可以使用 ActiveRecord Observer。我个人更喜欢这个而不是过滤器,因为你可以通过这种方式更多地解耦你的类。我倾向于喜欢适当的关注点分离,所以..
我假设一旦这些记录被停用,它们就不会再次激活。然而,无论如何,用于处理相反情况的附加功能的代码可以忽略不计。
PS 如果您不熟悉
&:handler
语法,它只是映射到可枚举中每个项目的函数或变量的快捷方式。Nope, you've got the right approach, you just need a slight nudge. See example below.
You can also use an ActiveRecord Observer. I personally prefer this over a filter as you are decoupling your classes more this way. And I tend to like proper separation of concerns, so..
I'm assuming once these records are deactivated, they will not become active ever again. Regardless, however, the code for additional functionality to handle the opposite case is negligible.
P.S. If you're not familiar with the
&:handler
syntax, it's simply a shortcut for mapping to function or variable per item in an enumerable.