Rails具有一个模型的许多模型的多个日期字段,属于另一个模型的日期之间



设置:我有一个 job PRICE 模型,其中作业有两个字段 start_date and end_date >Price 有另一个日期字段有效_AT JOB HAS_MANY 价格通过区域。我正在使用 by_star GEM,该GEM允许查询 indimes ,这些查询仅在模型中的定义字段之间获取记录。

我需要所有价格,均介于作业的 start_date end_date 之间。我相信,由于Rails_admin框架,我需要在 has_many中定义它,但无法确定完成它的最佳方法。这是模型:

class Job < ActiveRecord::Base
  belongs_to :region
  has_many :prices, through: :region
  # fields: start_date, end_date
end
class Price < ActiveRecord::Base
  belongs_to :region
  has_many :jobs, through: :region
  # fields: effective_at
end
class Region < ActiveRecord::Base
  has_many :jobs
  has_many :prices
end

我的实现方法有限在 Rails_admin 框架中。

def job_opis_prices
  prices.between_times(self.start_date, self.end_date)
end

我也尝试了:

class FracJob < ActiveRecord::Base
  has_many :opis_prices, through: :region do
    def during_job
      where(effective_at: between_times( start_time..end_time ))
    end
  end
end

任何帮助都将受到极大的赞赏!

我认为您可以使用default_scope,例如

class Price < ActiveRecord::Base
  default_scope { joins(:jobs).where('prices.created_at between jobs.created_at and jobs.updated_at') }
end

最新更新