Rails范围包含belongs_to和has_one到关系

时间:2016-01-26 20:23:45

标签: postgresql ruby-on-rails-4 model scope

class Employee < ActiveRecord::Base
  has_many :availabilities
  has_many :time_slots, through: :availabilities    
end

class TimeSlot < ActiveRecord::Base

  belongs_to :availability
  has_one :employee, through: :availability
end

class Availability < ActiveRecord::Base
  belongs_to :employee
  has_many :time_slots 
end

如何仅为具有特定员工的可用性的时间段创建范围?如果,员工ID被传递到范围。

class TimeSlot < ActiveRecord::Base

  belongs_to :availability
  has_one :employee, through: :availability

    scope :employee, -> (employee_id) { joins(:availability).where("availabilities.employee_id=?", employee_id) if employee_id.present? }
end

0 个答案:

没有答案