[英]Rails sorting associated records
Using Rails 3.0.10 & Ruby 1.9.2. 使用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? 处理这个问题的正确方法是什么,以便调用book.pages将按顺序返回所有页面?
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. 这样,您不必自己指定Book#pages
方法,默认情况下仍会按page_number asc
排序。
for newer versions of Rails, the syntax has changed: 对于较新版本的Rails,语法已更改:
class Book < ActiveRecord::Base
has_many :pages, -> { order "page_number asc" }
end
class Page < ActiveRecord::Base
belongs_to :book
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.