mysql - Return first record per group -


how can grab activerecord::relation object contains records each record first author each book.

# models class author < activerecord::base   has_many :authors_books end  class authorsbook < activerecord::base   belongs_to :author   belongs_to :book end  class books < activerecord::base   has_many :authors_books end 

@author_books = authorsbooks.all

example rows/records returned @author_books.all

author_id    book_id    3           1    2           1    3           1    4           1    1           2    1           3    2           4    3           4 

now want grab first author per book:

should return this:

author_id    book_id    3           1    1           2    1           3    2           4 

# returns array of active record objects ary_authorbook_objs = authorsbook.all.group_by(&:book_id).collect{|k,v| v.first}  # transforms array of active record objects 1 activerecord::relation object active_relation_object = authorsbook.where(id: ary_authorbook_objs.map(&:id)) 

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -