activerecord - Rails Associations has_one Latest Record -


i have following model:

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'    delegate :position, to: :current_revision    def current_revision     self.revisions.order('created_at desc').first   end end 

where current_revision created revision. possible turn current_revision association can perform query section.where("current_revision.parent_section_id = '1'")? or should add current_revision column database instead of trying create virtually or through associations?

i understand want sections last revision of each section has parent_section_id = 1;

i have similar situation, first, sql (please think categories sections you, posts revisions , user_id parent_section_id -sorry if don't move code need have go):

select categories.*, max(posts.id) m `categories`  inner join `posts`  on `posts`.`category_id` = `categories`.`id`  `posts`.`user_id` = 1 group posts.user_id having m = (select id posts category_id=categories.id order id desc limit 1) 

and query in rails:

category.select("categories.*, max(posts.id) m").joins(:posts).where(:posts => {:user_id => 1}).group("posts.user_id").having("m = (select id posts category_id=categories.id order id desc limit 1)") 

this works, ugly, think best way "cut" query, if have many sections problem while looping trough them; can place query static method, , also, first idea, have revision_id inside of sections table optimize query, drop normalization (sometimes needed), , have updating field when new revision created section (so if going making lot of revisions in huge database maybe bad idea if have slow server...)

update i'm hehe, making tests, , check out:

def last_revision     revisions.last end  def self.last_sections_for(parent_section_id)   ids = section.includes(:revisions).collect{ |c| c.last_revision.id rescue nil }.delete_if {|x| x == nil}    section.select("sections.*, max(revisions.id) m")          .joins(:revisions)          .where(:revisions => {:parent_section_id => parent_section_id})          .group("revisions.parent_section_id")          .having("m in (?)", ids) end 

i made query , worked tables (hope named params, same rails query before change query in having optimization); watch out group; includes makes optimal in large datasets, , sorry couldn't find way make relation has_one, go this, reconsider field mention @ beginning.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -