I have two models, an School model and Price model. Every school has a price. I would like to return in the search result school with its prices. I am using rails and sunspot.
School-controller:
class SchoolsController < ApplicationController
def index
@query = params[:search]
@search = School.search do
fulltext params[:search]
paginate :page => params[:page], :per_page => 7
end
@results = @search.results
end
end
School-model:
class School < ActiveRecord::Base
has_many :prices
# sunspot search
searchable do
text :name, :locality
end
end
Index – view
<% for result in @results %>
<tr>
# School name, from the school-model
<td><h3><%= link_to result.name, result %></h3></td>
# School price, from the price-model
<td><h3><%= result.prices.min %> kr</h3></td>
</tr>
<% end %>
How do I return for every school its prices, with sunspot?
Maybe you can do eager loading with
:include:Additionnal:
If a School can only have one Price, you should replace
has_many :priceswithhas_one :pricein your School model. After doing this, you could access to the price you want by doing this:result.price.min(take a look at number_to_currency, you could be interested in this Helper)