简体   繁体   中英

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

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.

for newer versions of Rails, the syntax has changed:

class Book < ActiveRecord::Base
    has_many :pages, -> { order "page_number asc" }
end

class Page < ActiveRecord::Base
  belongs_to :book
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM