【发布时间】: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