【问题标题】:ROR: Creating a method with a parameterROR:创建带参数的方法
【发布时间】:2017-05-10 09:35:33
【问题描述】:

我有一个管理员仪表板,其中显示过去 24 小时、7 天、28 天等创建的帖子。

def index
  @1DayPosts = Post.where(created_at: 1.days.ago..DateTime.now).count 
  @7DaysPosts = Post.where(created_at: 7.days.ago..DateTime.now).count 
  @28DaysPosts = Post.where(created_at: 28.days.ago..DateTime.now).count 
end

我怎样才能把它变成一行?类似于以下内容:

def index
  @calculatePosts(a) = Post.where(created_at: a.days.ago..DateTime.now).count 
end

那么在视图中我可以这样做:

=@calculatePosts(1)

或者我需要创建一个新方法吗?

def calculatePosts(a)
    @calculatePost = Post.where(created_at: a.days.ago..DateTime.now).count
end

然后我将如何在索引视图中调用它?

【问题讨论】:

    标签: ruby-on-rails ruby methods


    【解决方案1】:

    最好的办法是在 Post 模型上创建一个范围。

    class Post ...
    
      scope :last_x_days, -> (x) { where(created_at: x.days.ago..Time.zone.now) }
    end
    

    然后你可以在任何地方调用它,像这样在你的视图或控制器中。

    @last_10_days = Post.last_x_days(10).count
    

    编辑:

    你也可以这样做,但作用域应该是可链接的,所以不鼓励这样做,虽然没有错。

    scope :last_x_days_count, -> (x) { where(created_at: x.days.ago..Time.zone.now).count }
    

    【讨论】:

    • 感谢您的解决方案!在控制器中调用 @last_10_days = Post.last_x_days(10).count 然后在视图中调用 @last_10_days 是更好的做法吗?还是在视图中调用@last_10_days = Post.last_x_days(10).count 更好?还是没关系?
    • 没关系,直接在视图中调用Post.last_x_days(10).count就可以了,不需要@last_10_days,除非你在视图的多个地方都用到了。
    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多