I detect N + 1 in my project.
i have this two models
class Person
has_one :profile
delegate :first_name, :middle_name, :last_name, :full_name, to: :profile
searchable do
text :first_name, stored: true
text :middle_name, stored: true
text :last_name, stored: true
text :full_name, stored: true
end
end
class Profile
delegate :first_name, :middle_name, :last_name, :full_name, to: :profile
def full_name
#some code that will output full name
end
end
this is my controller for Person
def index
args = search_params
search = person_search(args)
@persons = search.results
end
def persons_search(args)
fulltext_fields = %i[first_name last_name full_name].freeze
Person.search do
if params.key?(:q)
fulltext params[:q], fields: fulltext_fields, query_phrase_slop: 0, minimum_match: 2 do
fulltext_fields.each { |field| highlight field, max_snippets: 3, fragment_size: 100 }
end
end
fulltext_fields.each do |field|
fulltext params[field], fields: field, query_phrase_slop: 0, minimum_match: 3 if params.key?(field)
end
end
end
Okay now i explain the back end now lets go to the HTML
hers my table
tbody
- @members.each do |member|
tr
td.p-2 = member.reference_number
td.p-2 = member.first_name <----------- THIS IS THE N + 1
as you can see in my table i repeat to call the "first_name"(I have 5k record) my conclusion is to add the "first_name" in the search result so i dont call the association profile?
is this the proper way to do it??? any suggestion is open :)
in my understanding. i put include in search so the sunspot include the association. i use the bullet gem. thats why im come up in this problem.
i think my table render the search result association. not the rails association. feel free to comment. if my explanation is not correct. im also a noob thanks :)