Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails sorting associated records

Using Rails 3.0.10 & Ruby 1.9.2.

I have a Book model which has many Pages.

class Book < ActiveRecord::Base
  has_many :pages

  # is this right?
  def pages
    Page.order('page_number asc').find_all_by_book_id(:id)
  end
end

class Page < ActiveRecord::Base
  belongs_to :book
end

When I retrieve the pages of a book, I always want them ordered by their page number. What is the proper way to handle this so that calling book.pages will return all pages in sequence?

When editing the book I also show the content of each page which can be edited. If I am using nested attributes would this return the pages in their proper sequence, assuming my previous question is resolved?

<%= form_for [@book, @pages] do |f| %>
  <%= f.fields_for :pages do |page| %>
    do something
  <% end %>
<% end %>

Thanks

like image 363
tollbooth Avatar asked Dec 27 '22 21:12

tollbooth


1 Answers

I believe you could actually specify the default order directly on the association declaration:

class Book < ActiveRecord::Base
    has_many :pages, :order => "page_number asc"
end

class Page < ActiveRecord::Base
  belongs_to :book
end

This way, you won't have to specify the Book#pages method yourself, and it will still be ordered by page_number asc by default.

like image 144
Frost Avatar answered Jan 08 '23 16:01

Frost