我想在模型关联中添加另一列 例如,请参阅http://guides.rubyonrails.org/v2.3.11/association_basics.html#the-has-many-through-association 现在我有一个新列也需要检查
医师
id
name
organization_id (new one)
约会
id
physician_id
patient_id
organization_id (new one)
appointment_date
患者
id
name
organization_id (new one)
我的要求是,如果三个表中的任何一个具有不同的organization_id,则该关联不起作用。
在控制器中,我使用的是代码: @all_patients = Physician.find_by_id_and_organization_id(params [:id],params [:orgId])。病人
让所有患者都属于医生并在UI上显示它们。
如果有一些脏数据,表约会和患者可能有不正确的organization_id。我想要的是UI不应该显示organization_id不是预期的数据。
例如,我在db中有数据说:
医生:
1,“医师1”,1
2,“医师2”,1
约会
1,1,1,1,2013-1-1
2,1,1,1,1,2013-1-1
3,1,3,1,2013-1-1
4,1,4,2,1137-1-1
患者
1,“患者1”,1
2,“患者2”,2
3,“患者3”,1
3,“患者4”,1
如果我使用的是Physician.find_by_id_and_organization_id(1,1)。患者,我希望得到以下患者
1,“患者1”,1
但现在我不知道如何配置模型关系,我得到了整个患者数据。
那么,如何配置模型?
答案 0 :(得分:0)
表appointments
中不需要额外的列。
在您的约会模型中,您可以进行额外的验证回调并确保患者和医生都属于同一组织:
class Appointment < ActiveRecord::Base
validate :have_to_be_in_the_same_organization
def have_to_be_in_the_same_organization
unless Patient.find(patient_id).organization_id == Physician.find(physician_id).organization_id
errors.add(:base, "The physician and the patient must be in the same organization to create an appointment!")
end
end
end
解决方案2:
如果您不希望它呈现任何错误,而是您想将其重定向到某个地方而不尝试创建该约会,则可以before filter
对create
操作执行appointmentscontroller
1}}:
class AppointmentsController < ActiveRecord::Base
before_filter :have_to_be_in_the_same_organization, :only => [:create]
def have_to_be_in_the_same_organization
unless Patient.find(params[:patient_id]).organization_id == Physician.find(params[:physician_id]).organization_id
redirect_to somewhere_path
end
end
end