【问题标题】:ruby on rails activate post on typical dateruby on rails 在典型日期激活帖子
【发布时间】:2017-03-28 23:40:56
【问题描述】:

我想在典型日期激活帖子(由用户安排) 并更新模型中的数据

例如。

Post schema
t.string :title
t.text :body
t.datetime :valid_from
t.datetime :valid_until
t.string :act_status, default: "padding #["pending", "activate", "expired"]

每个帖子都有 valid_from、valid_until 和 act_status

act_status 有 3 个阶段(待定、激活和过期)

用户填写所有信息,

当 "Time.now" 遇到 "valid_from" 时,帖子将对所有用户有效,并且它的 "act_status" 将变为 "activate" (@post.act_status = "activate")

当“Time.now”遇到“valid_until”时,帖子对其他用户无效,“act_status”将变为“expired”(@post.act_status = “expired”)


我的问题是,rails 如何在典型日期自动更改值。

在我看来,我可以在“用户”执行某些操作时更改值(触发某些操作,例如 CRUD)

但在我的情况下,用户只是保存价值,rails 应该触发该操作。

我没有任何想法来解决它。

如果您有一些说明或指南,请告诉我

谢谢..


  • 此外,在模型中存储“act_status”选项是否有效?

    Post.rb

    validates :act_status, inclusion: { in: %w(padding activate finish) }
    

【问题讨论】:

标签: ruby-on-rails schedule canactivate


【解决方案1】:

您不需要任何 act_status,只需创建范围并显示您想要的项目。

# in your model
scope :pending, -> { where('valid_until < now()') }
scope :active, -> { where('now() between valid_from AND valid_to') }
scope :expired, -> { where('valid_from > now()') }


# in your controller
@pending_posts = Post.pending
@active_posts = Post.active
@expired_posts = Post.expired

【讨论】:

  • 感谢冰人。这对我帮助很大。我认为当我希望用户在一段时间内只能激活一个帖子时,act_status 是必要的。例如,两个帖子不能同时激活。如果我想添加这个想法,你有什么建议吗?
  • 很高兴听到,如果它解决了您的问题,请将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多