Ruby on rails 如何从类数组调用属性

Ruby on rails 如何从类数组调用属性,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我正在尝试创建一个方法,该方法获取日期并将指定的天数添加到该日期上 目前我无法调用指定的日期 我有一个Plant类,它有很多天仍然可以销售,Period类也有很多天仍然可以销售 用户创建工厂时,可以添加DaysTillSellables,然后选择时段,然后输入天数 我首先需要检查日期在哪个时段,然后返回那个时段。目前正在这样做 def current_period return unless completed_at_week.between?(period.start_week, pe

我正在尝试创建一个方法,该方法获取日期并将指定的天数添加到该日期上

目前我无法调用指定的日期

我有一个Plant类,它有很多天仍然可以销售,Period类也有很多天仍然可以销售

用户创建工厂时,可以添加DaysTillSellables,然后选择时段,然后输入天数

我首先需要检查日期在哪个时段,然后返回那个时段。目前正在这样做

def current_period
    return unless completed_at_week.between?(period.start_week, period.finish_week)
    index_days_till_sellables_on_period_id
  end
然后找到与该期间相关的可销售天数,最后调用从该期间开始的天数

下面是我试图调用它的类的代码

 class Potting < ApplicationRecord
  belongs_to :batch, inverse_of: :pottings
  validates :plant_count, :completed_at, presence: true

  enum germination_result: { light: 0, medium: 1, full: 2 }

  def pottings_completed_at
    "Week #{completed_at.strftime('%U').to_i}/#{completed_at.strftime('%Y').to_i}"
  end

  def completed_at
    super || Time.zone.today
  end

  def completed_at_week
    completed_at.strftime('%U')
  end

  def current_period
    return unless completed_at_week.between?(period.start_week, period.finish_week)
    index_days_till_sellables_on_period_id
  end

  def period_days
    plant.days_till_sellables.find_by(period: :current_period).&current_period.days
  end

  def ready_for_sale
    completed_at + period_days
  end
end
我在下面添加了更多代码,以便为类提供更好的上下文

class DaysTillSellable < ApplicationRecord
  belongs_to :period, inverse_of: :days_till_sellables, foreign_key: :period_id
  belongs_to :plant, inverse_of: :days_till_sellables, foreign_key: :plant_id
  validates :days, presence: true
end


我认为您正在寻找:

class Potting
  belongs_to :plant, through: :batch
  ...
end

我的标题可能用词不正确,如果有更好的表达方式,请让我知道,谢谢,我会更改它。我不太清楚你的实际问题是什么。你想调用什么类方法?您将该方法作为参数提供什么?你期望的结果是什么?你目前的成绩如何?你有错误吗?如果是,有哪些错误?或者,你只是得到了一个没有意义的回报吗?我有一个period类,允许用户使用从1-52开始的开始周和结束周定义周期。周期不能与当前周期重叠。假设要检查当前的周期,通过查看完成的日期是否在期间范围内,如果在期间范围内,则应返回该期间id。下一种方法是查找与该期间id关联的可销售日期。然后我需要调用从该日期到可销售日期的日期,然后将其添加到已完成的日期,以便在ready_中显示该日期以供销售。我目前收到命名错误错误错误是未定义的局部变量或方法“plant”。从,Def period_days plant.days_到_selleble.find_byperiod::current_period&days endI建议在代码列表中包含更多的上下文,比如class plantclass Plant < ApplicationRecord has_many :batches, dependent: :destroy has_many :goals, dependent: :destroy has_many :days_till_sellables, dependent: :destroy, inverse_of: :plant belongs_to :organization accepts_nested_attributes_for :days_till_sellables, allow_destroy: true validates :genus, :species, :period_id, presence: true end
class Potting
  belongs_to :plant, through: :batch
  ...
end