Rails有许多可通过日期字段的一个模型属于其它型号日期间

问题描述:

设置: 我有一个工作价格模型,其中的工作有两个字段起始日期END_DATE价格有另一个日期字段effective_at工作 has_many 价格虽然一个地区。我正在使用by_star gem,它允许像between_times这样的查询,它只是获取模型中定义字段之间的记录。Rails有许多可通过日期字段的一个模型属于其它型号日期间

我需要的所有价格落在工作的起始日期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框架的方式来做到这一点有限的,否则我会做类似如下(其中工作正常,但韩元“T在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