如何声明将在所有操作中使用的实例变量?
How do I declare an instance variable that I will use in all of my actions?
我想在我的 NewsroomController
中的所有操作中使用此声明,如何以 DRY 方式执行此操作,而不是在每个操作中都声明它?
@num_posts_today = Post.published.posted_today.count
使用before_action
块。但是,请阅读 this 了解为什么它可能不是很棒。
我会将逻辑放在模型中。类似于:
def posts_published_today_count
self.published.posted_today.count
end
或者写一个class方法。
def self.published_today
self.published.posted_today
end
在你的控制器中:
Post.published_today.count
或浏览量:
@posts.published_today.count
你懂的。。。我写的东西没有测试过,大家可以随意修改。
我更喜欢在我的模型上不使用 .count 编写它,您可以将其用作范围,以防您将来需要使用。
我想在我的 NewsroomController
中的所有操作中使用此声明,如何以 DRY 方式执行此操作,而不是在每个操作中都声明它?
@num_posts_today = Post.published.posted_today.count
使用before_action
块。但是,请阅读 this 了解为什么它可能不是很棒。
我会将逻辑放在模型中。类似于:
def posts_published_today_count
self.published.posted_today.count
end
或者写一个class方法。
def self.published_today
self.published.posted_today
end
在你的控制器中:
Post.published_today.count
或浏览量:
@posts.published_today.count
你懂的。。。我写的东西没有测试过,大家可以随意修改。
我更喜欢在我的模型上不使用 .count 编写它,您可以将其用作范围,以防您将来需要使用。