如何在Rails 4中对关联数据进行排序

时间:2014-07-30 13:12:22

标签: ruby-on-rails ruby sorting ruby-on-rails-4

在我的应用中,我已经在 RailsCast 的帮助下成功完成了排序表。现在,在我的索引页面中,我有Store列,该列与Campaign模块相关联。我尝试了很多来对该列执行排序(asc / desc)顺序,但没有执行。

以下是几个代码:

型号: campaign.rb

class Campaign < ActiveRecord::Base
  belongs_to :store # association with stores table
  belongs_to :category
  belongs_to :location
  ......
  ......
end

型号: store.rb

class Store < ActiveRecord::Base
  has_many :campaigns
  ........
end

控制器: campaigns_controller.rb

class CampaignsController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @campaigns = Campaign.order(sort_column + " " + sort_direction)
  end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_campaign
      @campaign = Campaign.find(params[:id])
    end

    # methods for sorting
    def sort_column
      Campaign.column_names.include?(params[:sort]) ? params[:sort] : 'id'
    end

    def sort_direction
      %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'
    end

application_helper.rb

 def sortable(column, title = nil)
    title ||= column.titleize
    direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
    link_to title, :sort => column, :direction => direction
  end

查看 index.html.haml

%table
      %tr
        %th Sr. No.
        %th Store  # wanted to sort this column
        %th
          = sortable 'title','Title' # successfully sorted
- @campaigns.each do |campaign|
      %tr
         %td = campaign.title
         %td = (campaign.store.name rescue '')

将提供其他所需信息。在此先感谢:)

2 个答案:

答案 0 :(得分:1)

这是一次尝试,因为我不确定它如何与您的可排序方法一起使用,我在haml

时表现不佳
def index
  @campaigns = Campaign.joins(:store, :category).select(columns.values.join(",")).order([sort_column,sort_direction].join(" "))
end

def columns
 {"campaigns.id" => "campaigns.id",
  "campaigns.title" => "campaigns.title",
  "categories.name" => "categories.name as category_name",
  "stores.name" => "stores.name as store_name"}
end

def sort_column
  columns.keys.include?(params[:sort]) ? params[:sort] : 'campaigns.id'
end

在视图中

%table
  %tr
    %th Sr. No.
    %th 
      = sortable 'stores.name', 'Store'
    %th
      = sortable 'campaigns.title','Title' # successfully sorted
    %th
      = sortable 'categories.name', 'Category'
- @campaigns.each do |campaign|
  %tr
     %td = campaign.id
     %td = (campaign.store_name rescue '')
     %td = campaign.title
     %td = campaign.category_name

我希望这有帮助,因为你要我发一个答案,虽然我的评论意味着更具有方向性而不是具体回答。

答案 1 :(得分:0)

我非常感谢并感谢 engineersmnky 的指导,帮助以及他在这个问题上的宝贵时间。现在,通过使用 here

中的sorted gem,我找到了另一种最简单的排序方式

不需要太多代码..对于我已经完成的相关数据..

def index
  @campaigns = Campaign.joins(:store, :location).sorted(params[:sort], "title,stores.name,locations.name ASC:DESC?ASC")
end

并在 index.html.haml

%th
  = link_to_sorted "Store", 'stores.name'
%th
  = link_to_sorted "Location", 'locations.name'

完美无缺......:)