如何从类数组调用属性?日期累加天数方法实现遇阻求助
解决日期累加与周期匹配的问题
看起来你在处理植物售卖周期的日期计算问题,我来帮你梳理下思路和可行的解决方案:
1. 先确认模型关联的正确性
根据你的描述,DaysTillSellable是连接Plant和Period的关联模型,这一步是后续逻辑能跑通的基础,先把模型定义补全:
Plant 模型
class Plant < ApplicationRecord has_many :days_till_sellables has_many :periods, through: :days_till_sellables # 可选,方便直接通过植物获取关联周期 end
Period 模型
class Period < ApplicationRecord has_many :days_till_sellables has_many :plants, through: :days_till_sellables # 周期必须有时间范围才能判断日期归属,所以需要添加 start_date 和 end_date 字段 # 可以通过迁移生成:rails generate migration AddStartAndEndDateToPeriods start_date:date end_date:date # 之后运行 rails db:migrate 完成字段添加 end
DaysTillSellable 模型
class DaysTillSellable < ApplicationRecord belongs_to :plant belongs_to :period # 确保天数字段有效 validates :days, presence: true, numericality: { only_integer: true, greater_than: 0 } end
2. 实现 current_period 方法
这个方法的核心是根据传入的日期,找到当前植物对应的、包含该日期的周期,我们把它写在Plant类里:
class Plant < ApplicationRecord # ... 已有的关联定义 ... # 传入目标日期,默认使用今天 def current_period(target_date = Date.today) # 筛选出该植物关联的、时间范围覆盖目标日期的周期 periods.joins(:days_till_sellables) .where(days_till_sellables: { plant_id: self.id }) .where("periods.start_date <= ? AND periods.end_date >= ?", target_date, target_date) .first end end
3. 实现日期累加逻辑
拿到正确的周期后,就能获取对应的天数并计算最终的售卖日期了:
class Plant < ApplicationRecord # ... 已有的方法 ... def calculate_sellable_date(target_date = Date.today) # 先获取当前日期所属的周期 current_period = self.current_period(target_date) # 处理找不到对应周期的情况 unless current_period Rails.logger.warn "No matching period found for plant #{self.id} on #{target_date}" return nil end # 获取该植物在当前周期下的天数配置 days_config = days_till_sellables.find_by(period: current_period) # 处理未配置天数的情况 unless days_config&.days.present? Rails.logger.warn "No days configured for plant #{self.id} in period #{current_period.id}" return nil end # 完成日期累加并返回结果 target_date + days_config.days.days end end
4. 调用示例
现在你可以这样使用这些方法:
# 假设你已经获取了一个 plant 实例 plant = Plant.find(1) # 计算今天对应的售卖日期 sellable_date = plant.calculate_sellable_date # 或者指定某个具体日期计算 specific_date = Date.parse("2024-06-10") sellable_date = plant.calculate_sellable_date(specific_date)
可能的问题排查
如果你之前调用不了指定天数,大概率是这几个原因:
- 模型关联配置错误,导致
Plant无法正确关联到对应的DaysTillSellable记录 Period没有时间范围字段,无法判断日期属于哪个周期current_period方法没有限定是当前植物的周期,导致拿到了其他植物的周期配置
内容的提问来源于stack exchange,提问作者Tommy Tayler
相关产品推荐
相关产品推荐

