0

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?

pocopina
  • 3
  • 2

2 Answers2

0

So with Rubyist's answer it works. However, it didn't work until I un-nested the Rooms resource in routes.rb.

I don't understand why the nested route was causing a problem though.

pocopina
  • 3
  • 2
0

There's nothing wrong with anything you're doing in terms of Sunspot and Solr.

Your error in your view is because you are calling locations on a Room object, when it should be location (as a Room belongs to a Location).

The error about undefined method location_name for nil is because the Room instance you are trying to index doesn't have an associated Location (ie. @room.location is nil). You can either put the indexing in a conditional (eg. location.location_name if location.present? or use something like try (eg. location.try(:location_name)).

sevenseacat
  • 24,699
  • 6
  • 63
  • 88