[英]Ransack search on has_one :through (alias)
I'm attempting to use ransack to search for an attribute on a has_one association in a model. 我正在尝试使用ransack在模型中的has_one关联上搜索属性。
Currently in my model I have: 目前在我的模型中,我有:
class SurveyResponse < ActiveRecord::Base
belongs_to :course_schedule
has_one :instructor, through: :course_schedule
has_one :instructor_user, through: :instructor, foreign_key: "user_id", source: :user
I want to search by instructor_user's
name in my survey response view. 我想在我的调查回复视图中按
instructor_user's
名字进行搜索。 Should I be doing this with a ransacker? 我应该和洗劫者一起这样做吗? My understanding of Arel is very limited, but can I do something like this?
我对Arel的了解非常有限,但是我可以做这样的事情吗? (I know this doesn't work as it is..)
(我知道这是行不通的。)
def self.ransackable_attributes(auth_object)
[
'created_at',
'instructor_user_name'
]
end
ransacker :instructor_user_name, type: :string do
Arel.sql('string(survey_responses.instructor_user.last_name)')
end
In my survey response controller I currently have: 在我的调查响应控制器中,我目前有:
def index
@search_associations = [:course, :user]
@q = SurveyResponse.where(corporation_id: @corporation.id).ransack(params[:q])
@q.build_condition
@survey_responses = @q.result.includes(:course, :user, :course_schedule, :instructor, :instructor_user).order(created_at: :asc)
@survey_responses = paginate(@q)
end
Any help, resources, and guidance would be greatly appreciated. 任何帮助,资源和指导将不胜感激。
I don't think you need a ransacker specifically. 我认为您不需要特别的抢劫犯。 I believe in your view, inside a
search_form_for
you just simply could do: 我相信您的观点,在
search_form_for
内部,您可以做到:
<%= f.search_field :instructor_user_name %>
Also, in your controller instead of @survey_responses = paginate(@q)
I think you need @survey_responses = paginate(@survey_responses)
so you can paginate the responses not the ransack object (could be wrong on this based on what pagination gem you're using). 此外,在您的控制器,而不是
@survey_responses = paginate(@q)
我认为你需要@survey_responses = paginate(@survey_responses)
这样你就可以分页不响应的洗劫对象(基于什么分页宝石你”可能是错在这重新使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.