Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload