代码之家  ›  专栏  ›  技术社区  ›  mliebelt

用Rails中连接模型定义的顺序分页

  •  0
  • mliebelt  · 技术社区  · 15 年前

    • 我想按作者姓名,然后按书名对应用程序中存储的书籍进行排序。

    书和作者是具体的模型,对应的表格是资源和人。模式的相关部分是(我稍微简化了模型):

      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])
    

    1 回复  |  直到 15 年前
        1
  •  1
  •   Shadwell    15 年前

    考虑到一本书有多个作者,您需要决定如何确定应该使用哪个作者的名字来排列书单。

    可以添加关联 has_one :main_author, :class_name => 'Author' 给你的 Book people_ressources 或者你可以使用第一个作者:

    has_one :main_author, :through => :author_books, :order => 'sur_name'
    

    拥有那个 has_one sur_name 在那里:

    @books = Book.paginate(:order => "#{Author.table_name}.sur_name", 
                           :per_page => 15, 
                           :page => params[:page])