Rya*_*ing 6 model ruby-on-rails associations
我有一个Page包含许多Section模型的模型,它与一个SectionRevision通过相关联current_revision.从Page模型我想选择所有Sections在current_revision.parent_section_id不为零.
Section 模型:
class Section < ActiveRecord::Base
belongs_to :page
has_many :revisions, :class_name => 'SectionRevision', :foreign_key => 'section_id'
has_many :references
has_many :revisions, :class_name => 'SectionRevision',
:foreign_key => 'section_id'
belongs_to :current_revision, :class_name => 'SectionRevision', :foreign_key => 'current_revision_id'
delegate :position, to: :current_revision
def set_current_revision
self.current_revision = self.revisions.order('created_at DESC').first
end
def children
Section.includes(:current_revision).where(:section_revisions => {:parent_section_id => self.id})
end
end
Run Code Online (Sandbox Code Playgroud)
和Page型号:
class Page < ActiveRecord::Base
belongs_to :parent, :class_name => 'Page', :foreign_key => 'parent_page_id'
has_many :children, :class_name => 'Page', :foreign_key => 'parent_page_id'
belongs_to :page_image, :class_name => 'Image', :foreign_key => 'page_image_id'
has_many :sections
validates_uniqueness_of :title, :case_sensitive => false
def top_level_sections
self.sections.includes(:current_revision).where(:section_revisions => {:parent_section_id => "IS NOT NULL"})
end
end
Run Code Online (Sandbox Code Playgroud)
Page.top_level_sections是基于以下内容编写的:Rails,其中条件使用NOT NULL并且当前生成一个空数组.它无法正确检测"parent_section_id"是否为空.
我怎么写得Page.top_level_sections正确?
Rah*_*ali 11
试试这个:
self.sections.includes(:current_revision).
where("section_revisions.parent_secti??on_id IS NOT NULL")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16410 次 |
| 最近记录: |