【问题标题】:Rails: using find method to access joined tables for polymorphic relationshipsRails:使用 find 方法访问多态关系的连接表
【发布时间】:2010-05-26 13:31:39
【问题描述】:

好的,我有一个通用的 TimeSlot 模型,它处理时间跨度的 start_atend_at。几个模型由此派生,但我指的是这个问题中的一个:AppointmentBlock,它是Appointments 的集合。我想验证一个AppointmentBlock,以便在同一时间范围内没有为特定Employee 安排其他AppointmentBlocks。由于AppointmentBlockTimeSlot 具有多态关联,因此您必须通过TimeSlot 访问AppointmentBlockend_at,如下所示:appt_block.time_slot.start_at 这意味着我需要某种加入我的:conditions 进行我的find() 方法调用。到目前为止,这是我的代码:

#inside my time_slot.rb model
belongs_to :time_slot_role, :polymorphic => true

 

#inside my appointment_block.rb model
has_one :time_slot, :as => :time_slot_role, :dependent => :destroy
validate :employee_not_double_booked

def employee_not_double_booked
  unless self.employee_id
    # this find's condition is incorrect because I need to join time_slots to get access
    # to start_at and end_at. How can I do this?
    blocks = AppointmentBlock.find(:first,
      :conditions => ['employee_id = ? and (start_at between ? and ? or end_at between ? and ?)',
      self.employee_id, self.time_slot.start_at, self.time_slot.end_at,
      self.time_slot.start_at, self.time_slot.end_at])
    # pseudo code:
    # collect a list of appointment blocks that end after this
    # apointment block starts or start before this appointment
    # block ends that are also associated with this appointment
    # blocks assigned employee
    # if the count is great then 0 the employee has been double
    # booked.

    # if a block was found that means this employee is getting
    # double booked so raise an error
    errors.add "AppointmentBlock",
      "has already been scheduled during this time" if blocks
  end
end

由于AppointmentBlock 没有start_atend_at 我如何加入time_slots 表以使这些条件起作用?

【问题讨论】:

    标签: ruby-on-rails find join


    【解决方案1】:

    你可以在 find 上使用 :joins 参数,类似这样:

     blocks = AppointmentBlock.find(:first,
              :conditions => ['employee_id = ? and (time_slots.start_at between ? and ? or time_slots.end_at between ? and ?)',
                self.employee_id, self.time_slot.start_at, self.time_slot.end_at,
                self.time_slot.start_at, self.time_slot.end_at],
              :joins => 'join time_slots on time_slots.time_slot_role_id = appointment_blocks.id')
    

    【讨论】:

    • 感谢威廉,欢迎来到 StackOverflow!我忘记了一些关于我的多态关系的重要信息(参见我编辑的帖子)。我认为要完成这项工作,我需要'join time_slots on time_slots.time_slot_role_id = appointment_blocks.id'
    • 如果您使用我刚刚评论的部分编辑您的答案,我会接受您的答案。
    • 更改了代码以反映您的表结构。很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多