I'm attempting to use ransack to search for an attribute on a has_one association in a model.
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. Should I be doing this with a ransacker? My understanding of Arel is very limited, but can I do something like this? (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:
<%= 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.