【问题标题】:Ruby on Rails Activerecord Named Scope Criteria on Nested Model QuestionRuby on Rails Activerecord 在嵌套模型问题上命名范围标准
【发布时间】:2011-06-29 16:31:39
【问题描述】:

我有以下表格(仅显示主键和外键以及 udds 表中的名称):

employee    appointment    appointment_udds    udds
--------    -----------    ----------------    ----
id          id             id                  id
            employee_id    appointment_id      name
                           udds_id

我将模型中的关系设置如下:

employee.rb

has_many :appointments, :dependent => :destroy

appointment.rb

has_many :appointment_uddss, :dependent => destroy
belongs_to :employee

appointment_udds.rb

belongs_to :appointment
belongs_to :udds

udds.rb

has_many :appointment_uddss

所以我主要使用 Employee 模型,我试图在它的模型中创建一个命名范围来获取所有具有非空 udds 名称的记录,如下所示:

employee.rb

named_scope :with_udds, :include => :uddss, :conditions => "udds.name IS NOT NULL"

我希望调用 Employee.with_udds 以获取所有具有非空名称字段的 udd 的员工。这种关系对于 ActiveRecord 来说是否过于复杂,还是我的处理方式错误?


我也尝试将关系扩展到员工类中的 udds 表:

class Employee < ActiveRecord::Base
  acts_as_audited
  has_many :appointments, :dependent => :destroy
  has_many :appointment_uddss, :through => :appointments
  has_many :uddss, :through => :appointment_uddss

  named_scope :with_udds, :include => :uddss, :conditions => "udds.name IS NOT NULL"

然后在控制台中:

Employee.with_udds

返回一个空集(数据库中有 udds.name != null 的数据)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    明确列出包含:

    :include => { :appointments => { :appointment_uddss => :uddss } }
    

    【讨论】:

    • 在 Rails 3.1 中不推荐使用传递参数哈希
    • @Caley named_scope 在 Rails 3.0 中已被弃用,所以我认为这个问题适用于 2.x
    【解决方案2】:

    试试这个:

    class Employee < ActiveRecord::Base
      acts_as_audited
      has_many :appointments, :dependent => :destroy
      has_many :appointment_uddss, :through => :appointments
      has_many :uddss, :through => :appointment_uddss
    
      scope :with_udds, where("udds.name IS NOT NULL").includes(:udds)
    end
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多