我有以下表格(只显示主键和外键以及udds表格中的名称):
employee appointment appointment_udds udds
-------- ----------- ---------------- ----
id id id id
employee_id appointment_id name
udds_id
我在模型中设置的关系如下:
员工.rb
has_many :appointments, :dependent => :destroy
预约.rb
has_many :appointment_uddss, :dependent => destroy
belongs_to :employee
任命_udds.rb
belongs_to :appointment
belongs_to :udds
udds.rb
has_many :appointment_uddss
所以我主要使用Employee模型,我试图在它的模型中创建一个命名范围,以获取所有具有非空udds名称的记录,比如:
员工.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"
然后在控制台中:
员工。有附加
返回一个空集(数据库中有udds.name!=null的数据)
明确列出包含:
:include => { :appointments => { :appointment_uddss => :uddss } }
试试这个:
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