我有以下表格(仅显示主键和外键以及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模型,我试图在它的模型中创建一个命名范围,以获取所有具有非null udds名称的记录,如下所示:
employee.rb
named_scope :with_udds, :include => :uddss, :conditions => "udds.name IS NOT NULL"
我希望调用 Employee.with_udds 来获取所有具有非空名称字段的员工的udds。对于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的数据)
答案 0 :(得分:0)
明确列出包含:
:include => { :appointments => { :appointment_uddss => :uddss } }
答案 1 :(得分:0)
试试这个:
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