0

I have a live site that has many Book models. I've recently added a Settings model that belongs_to each Book.

Now when I'm writing code to use the book.settings method, how do I avoid checking ‘book.settings.nil?’ or doing ’book.settings || book.create_settings’ in every call? The settings model has some defaults I can use.

4

2 回答 2

1

更新:较早的答案建议使用后提交挂钩将默认设置添加到书籍。根据评论,这不是问题。我已经删除了较早的答案,以避免读者混淆。

您可以使用将在生产服务器上运行一次的 rake 任务来修复没有默认设置的书籍。

于 2013-08-16T13:26:29.497 回答
0

为什么不将这些条件放在自定义方法上,并调用它而不是调用settings,如下所示:

def default_settings
  self.settings || self.create_settings
end

然后你这样称呼它:

@book.default_settings

nil?里面也可以查default_settings

于 2013-08-16T14:49:08.613 回答