Ruby on rails RubyonRailsActiveRecord命名范围标准关于嵌套模型问题
以下表格仅显示主键和外键以及udds表格中的名称:Ruby on rails RubyonRailsActiveRecord命名范围标准关于嵌套模型问题,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,以下表格仅显示主键和外键以及udds表格中的名称: employee appointment appointment_udds udds -------- ----------- ---------------- ---- id id id id employee_id appointment_id name
employee appointment appointment_udds udds
-------- ----------- ---------------- ----
id id id id
employee_id appointment_id name
udds_id
我在模型中设置了如下关系:
employee.rb
appointment.rb
预约_udds.rb
udds.rb
因此,我主要使用Employee模型,并尝试在其模型中创建一个命名范围,以获取所有具有非空udds名称的记录,如下所示:
employee.rb
我希望调用Employee.with_udds来获取所有UDD中包含非空名称字段的员工。这种关系对ActiveRecord来说太复杂了,还是我走错了方向
我还尝试将关系扩展到employee类中的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的Employee.com
返回一个空集。udds.name!=db中为空,明确列出包含项:
: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
在Rails 3中,不推荐传递参数散列。1@CaleyRails3.0中不推荐使用命名的_范围,因此我假设这个问题适用于2.x
has_many :appointment_uddss
named_scope :with_udds, :include => :uddss, :conditions => "udds.name IS NOT NULL"
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"
: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