【问题标题】:Rails using has_many through associationsRails 通过关联使用 has_many
【发布时间】:2013-05-06 07:55:49
【问题描述】:

这是一个菜鸟问题——我要访问 3 个关联的表。

患者模型具有:

has_many :charts
has_many :providers, :through => :charts

Provider 模型有:

has_many :charts 
has_many :patients, :through => :charts

图表模型有:

belongs_to :patient
belongs_to :provider

我拉出 current_user.id 来设置 @provider 工作正常。

@provider = Provider.where(:user_id => current_user.id).first    

然后我使用该@provider.id 来创建我需要的图表哈希,它也可以工作

@charts = Chart.where(:provider_id => @provider.id)

但是当我尝试从@charts 散列创建患者散列时,它会中断....

@patients = Patient.where(:id => @charts.patient_id)

说 '未定义的方法 `patient_id' for #' [patient_id 是图表表中的列之一]

我做错了什么?帮助!

【问题讨论】:

    标签: ruby ruby-on-rails-3.2 has-many-through


    【解决方案1】:

    试试这个:

    @patients = Patient.where(:id => @charts.map(&:patient_id))
    

    @charts 集合不会自动收集其成员的患者 ID。其他两个查询有效,因为您正在对单个记录进行操作,而在最后一个查询中,您正在对第二个查询返回的集合进行操作。

    【讨论】:

      【解决方案2】:

      我认为要访问一个列,您可能需要执行以下操作:

      @patients =  Patient.where(:id => @charts[:patient_id])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        相关资源
        最近更新 更多