簡體   English   中英

Rails:我如何渴望通過實例方法對負載關聯進行排序?

[英]Rails: How can I eager load associations with sorting through instance an method?

class Newsroom < ActiveRecord::Base
  has_many :blog_posts
  has_many :quote_posts
end

class BlogPost < ActiveRecord::Base
  belongs_to :newsroom
end 

class QuotePost < ActiveRecord::Base
  belongs_to :newsroom
end

我想要一個實例方法,這樣我就可以執行@ newsroom.posts來獲取由created_at排序的blog_posts和quote_posts的集合。

def posts
   @posts ||= #load and sort blog_posts, quote_posts, etc
end

最佳和最有效的方法是什么? 我研究了使用default_scope的方法,例如:

default_scope :include => [:blog_posts, :quote_posts]

def posts
  @posts ||= [blog_posts + quote_posts].flatten.sort{|x,y| x.created_at <=> y.created_at}
end

但是,如果可能的話,我寧願在數據庫級別進行排序。 關於如何做到這一點的任何建議? 謝謝。

嘗試這樣的事情:

#app/models/newsroom.rb

scope :ordered_posts, lambda {
  includes(:blog_posts,:quote_posts) & BlogPost.order("created_at asc") & QuotePost.order("created_at asc")
}

ARel應該能夠處理包含的報價和博客文章的排序。 您可以通過在BlogPost和QuotePost模型中都具有由created_at排序的范圍,然后在Newsroom#ordered_posts方法中使用這些范圍來稍微清理一下范圍。

我最終使用了一個多態的post模型。 這似乎給了我我想要的額外模型/表格的不足之處。 我使用委托將特定的屬性獲取方法傳遞給正確的模型。

class Newsroom < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belong_to :blog_post, :polymorphic => true

  delegate :title, :author, :etc, :to => :postable
end

class BlogPost < ActiveRecord::Base
  has_one :post, :as => :postable
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM