【问题标题】:Ruby On Rails Association with addition columnRuby On Rails 关联与添加列
【发布时间】:2013-04-17 10:12:16
【问题描述】:

我想在模型关联中添加另一列 例如见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]).patients

让所有患者都属于医生并在 UI 上显示。 在某些脏数据的情况下,表约会和患者可能具有不正确的组织 ID。我想要的是 UI 不应该显示 organization_id 不是预期的数据。 例如,我在 db 中有数据说:

医生:
1、《医师1》、1
2、《医师2》、1

约会
1、1、1、1、2013-1-1
2、1、2、1、2013-1-1
3、1、3、1、2013-1-1
4、1、4、2、2013-1-1

患者
1, "病人 1", 1
2, 《病人 2》, 2
3、《病人3》、1
3、“患者 4”、1

如果我使用的是 Physician.find_by_id_and_organization_id(1,1).patients,我希望得到以下患者
1, "病人 1", 1
但现在我不知道如何配置模型关系,我得到了整个患者数据。

那么,如何配置模型?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    您不需要在表 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:

    如果您不希望它呈现任何错误,而是希望将其重定向到某个位置而不尝试创建该约会,您可以在 create 中的 create 操作中执行 before filter appointmentscontroller

    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
    

    【讨论】:

    • 此验证出现错误。我不希望它提示错误。我希望它什么都不返回。就像没有找到数据一样。再次感谢。
    • 你想把它重定向到某个地方吗?使问题更清楚。显示来自 appointmentscontrollercreate 操作
    • 在控制器中,我使用 Physician.find_by_id_and_organization_id(params[:id], params[:orgId]).patients 让所有患者属于医生以显示在 UI 上。在某些脏数据的情况下,表约会和患者可能具有不正确的组织 ID。我想要的是 UI 不应该显示 organization_id 不是预期的数据。
    • 请用新信息编辑您的问题,我没有得到您想说的内容
    • 抱歉让您感到困惑,现在我更新了我的问题。非常感谢你帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多