You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails 6中实现文章定时发布与状态自动控制?

解决文章定时发布的published字段自动设置问题

问题根源及修复步骤:

  1. 移除多余的attr_accessor :published
    数据库中已经存在published字段,ActiveRecord会自动生成对应的属性访问器,手动添加attr_accessor会覆盖这一机制,导致数据库字段无法被正确读写,直接删掉这一行即可。

  2. 修正赋值运算符
    你的publicaciones方法里误用了比较运算符==,这只会判断值是否相等,不会给字段赋值。必须改成单等号=才能完成赋值操作。

  3. 正确处理datetime与Date的比较
    inicio_publicacion是datetime类型(包含时分秒),直接和Date.today比较会因为时间部分不匹配而失效,需要将inicio_publicacion转换为Date类型后再对比。

修正后的完整模型代码:

class Post < ApplicationRecord
  before_save :publicaciones

  def publicaciones
    # 基础逻辑:发布开始日期等于今日时设为已发布
    self.published = self.inicio_publicacion.to_date == Date.today

    # 可选进阶逻辑:当前时间处于发布区间内则设为已发布
    # if self.inicio_publicacion.present?
    #   self.published = Time.current >= self.inicio_publicacion
    #   # 同时判断结束时间(如果有设置)
    #   self.published &&= Time.current <= self.fin_publicacion if self.fin_publicacion.present?
    # else
    #   self.published = false # 未设置发布时间则默认不发布
    # end
  end
end

内容的提问来源于stack exchange,提问作者Arturo Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:57:16