使用Ransack对父级父级的属性进行排序

时间:2014-07-06 06:16:42

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

我知道如何使用Ransack的真棒sort_link方法用于父属性,但是当我将相同的逻辑推断为祖父母的属性时,它不起作用(我可以点击链接,不进行排序)。

层次结构如下:Signup has_many Request has_many Transaction。我正在从事务角度进行搜索。

控制器代码:

def index
  @q = Transaction.ransack(params[:q])
  @transactions = @q.result.includes(:request => :signup)
end

查看代码:

<th><%= sort_link(@q, 'requests.signup.email', "Email") %></th>
<th><%= sort_link(@q, 'requests.pickupdate', "Pick up date") %></th>
<th><%= sort_link(@q, 'requests.returndate', "Returndate") %></th>

顺便提一下,搜索代码(例如:request_returndate_eq)很好,只是排序不起作用。

型号代码:

class Signup < ActiveRecord::Base
  has_many :requests
end

class Request < ActiveRecord::Base
  belongs_to :signup
  has_many :transactions, dependent: :destroy
end

class Transaction < ActiveRecord::Base
  belongs_to :request
end

控制台输出

首次单击以升序排序(尽管任何点击它总是产生200响应,即使视图实际上没有改变)

Started GET "/admin/transactions?q%5Bs%5D=requests.signups.email+asc" for 127.0.0.1 at 2014-07-07 13:40:16 -0700
  Processing by TransactionsController#index as HTML
    Parameters: {"q"=>{"s"=>"requests.signups.email asc"}}
    Rendered layouts/_flash.html.erb (0.6ms)
      (0.4ms)  SELECT "transactions"."name" FROM "transactions"
    Transaction Load (0.6ms)  SELECT "transactions".* FROM "transactions"
    Request Load (0.3ms)  SELECT "requests".* FROM "requests"  WHERE "requests"."id" IN (11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)
    Signup Load (0.1ms)  SELECT "signups".* FROM "signups"  WHERE "signups"."id" IN (4, 5, 1, 2)
  Rendered transactions/index.html.erb within layouts/application (74.3ms)
Completed 200 OK in 85ms (Views: 81.7ms | ActiveRecord: 1.4ms)

1 个答案:

答案 0 :(得分:0)

您可以使用delegate来避免在视图中使用父级或父级表达式。

模型

class Transaction < ActiveRecord::Base
  belongs_to :request
  delegate :email, to: :request, prefix: true
end

交易视图代码:

<th><%= sort_link(@q, 'request_email', "Email") %></th>