如何从类数组

时间:2018-05-02 01:59:15

标签: ruby-on-rails activerecord

我试图制作一个获取日期的方法,并将指定的天数添加到其中。

目前我无法拨打指定日期。

我有一个具有多个DaysTillSellables的Plant类,Period类has_many DaysTillSellable也是。

当用户创建工厂时,他们可以添加DaysTillSellables,然后选择一个时段,然后输入天数。

我首先要检查日期是哪个时段,然后返回该时段。目前正在尝试这样

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

然后找到与该时期相关的可销售天数,最后从那个

中调用日期

以下是I类尝试在

中调用它的代码
 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 Period < ApplicationRecord
  has_many :days_till_sellables, dependent: :destroy, inverse_of: :period
  belongs_to :organization

class 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

1 个答案:

答案 0 :(得分:0)

我认为你在寻找:

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