Using Ransack to sort attributes for parent of parent

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 11:49:12

问题


I know how to use Ransack's awesome sort_link method for parent attributes, but when I extrapolate the same logic to the attributes of the grandparent, it's not working (I can click the link, just no sorting happens).

Hierarchy goes like this: Signup has_many Request has_many Transaction. I'm searching in from the Transaction perspective.

Controller code:

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

View code:

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

Incidentally, the search code (e.g., :request_returndate_eq) is fine, it's just the sorting that's not working.

Model code:

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

Console output

On first click to sort ascending (though with any click it always produces a 200 response, even though the view doesn't actually change)

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:


You can using delegate to avoid parent or parent expression in view.

Model

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

Transaction View code:

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


来源:https://stackoverflow.com/questions/24593225/using-ransack-to-sort-attributes-for-parent-of-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!