I'm working on getting my head around Sunspot and am having trouble accessing data from an associated model in Sunspot search results.
I have a Room model with fields: id, room_name, capacity, location_id. It looks like this:
class Room < ActiveRecord::Base
belongs_to :location
searchable do
text :room_name
end
end
And a Location model with fields: id, location_name. It looks like this:
class Location < ActiveRecord::Base
has_many :rooms
end
I have a Search Controller that looks like this:
class SearchController < ApplicationController
def later
@search = Sunspot.search(Room)
@results = @search.results
end
end
And I'm trying to render a view that looks like this:
<% @results.each do |result| %>
<%= result.room_name %>
<%= result.capacity %>
<%= result.location.location_name %>
<% end %>
However I get the following error when I visit /search/later
NoMethodError in Search#later
Showing ./app/views/search/later.html.erb where line #4 raised:
undefined method `locations' for #<Room id: 1, room_name: "Room 1", capacity: 6, location_id: 1>
Without line 4 this works perfectly, the problem seems to be with where I'm reaching out to the Location model.
My understanding was that the @results
variable should be a valid ActiveRecord object and would allow me to access data from the associated model, in this case Location?