按照 Rails 中连接模型定义的顺序进行分页
目前,我的 Rails 应用程序 (Rails 2.3.5) 中存在以下问题:
- 我想按作者姓名和书名对存储在应用程序中的书籍进行排序。
Book和Author是具体模型,对应的表是Ressources和People。模式的相关部分是(我稍微简化了模型):
create_table "people", :force => true do |t|
t.string "sur_name"
t.string "pre_name"
...
t.string "type"
end
create_table "people_ressources", :id => false, :force => true do |t|
t.integer "ressource_id"
t.integer "person_id"
end
create_table "ressources", :force => true do |t|
t.string "type"
t.string "title"
end
为了显示书籍列表,我使用了以下分页器:
@books = Book.paginate(
:order => 'title', :per_page => 15, :page => params[:page])
我现在的问题是:应该如何构建分页器,以便书籍按顺序排列按标题,但首先按作者(==人) sur_name?如果这不容易实现,那么什么构造可以允许将书籍和作者存储为单独的实体,但又允许获得具有定义顺序的分页器?
I have currently the following problem in my Rails application (Rails 2.3.5):
- I want to sort books stored in the application by the author name, then the title of the book.
Book and Author are concrete models, the corresponding tables are Ressources and People. The relevant portion of the schema is (I have stripped down the model a bit):
create_table "people", :force => true do |t|
t.string "sur_name"
t.string "pre_name"
...
t.string "type"
end
create_table "people_ressources", :id => false, :force => true do |t|
t.integer "ressource_id"
t.integer "person_id"
end
create_table "ressources", :force => true do |t|
t.string "type"
t.string "title"
end
To show the list of books, I have used the following paginator:
@books = Book.paginate(
:order => 'title', :per_page => 15, :page => params[:page])
My question now is: How should the paginator be constructed so that the books are ordered not by title, but first by author (== person) sur_name? And if that is not easily reachable, what construct would allow to store books and authors as separate entities, but would allow to get a paginator with the defined order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
鉴于您的一本书有多个作者,您需要决定如何确定应使用哪个作者的姓名来对图书列表进行排序。
您可以添加关联
has_one :main_author, :class_name => 'Author'
到您的Book
类中,按照您的意愿进行定义(也许在people_ressources
中有一个主要作者字段,或者您只使用可用的第一个作者:
has_one
关联意味着您可以将其包含在分页中并根据sur_name
进行排序:Given that you have multiple authors for a book you would need to decide how you determine which is the author whose name should be used to order the list of books.
You could add an association
has_one :main_author, :class_name => 'Author'
to yourBook
class defined however you wish (maybe there is a primary author field inpeople_ressources
or maybe you just use the first author available:Having that
has_one
association means that you can include that in the pagination and order against thesur_name
there: