0

我正在努力了解太阳黑子,但在访问太阳黑子搜索结果中关联模型的数据时遇到问题。

我有一个带有字段的房间模型:id、room_name、容量、location_id。它看起来像这样:

class Room < ActiveRecord::Base

  belongs_to  :location

  searchable do
    text :room_name
  end

end

还有一个带有字段的位置模型:id、location_name。它看起来像这样:

class Location < ActiveRecord::Base

  has_many :rooms

end

我有一个看起来像这样的搜索控制器:

class SearchController < ApplicationController

  def later
    @search = Sunspot.search(Room)
    @results = @search.results
  end

end

我正在尝试渲染一个看起来像这样的视图:

<% @results.each do |result| %>
  <%= result.room_name %>  
  <%= result.capacity %>
  <%= result.location.location_name %> 
<% end %>

但是,当我访问 /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>

如果没有第 4 行,这可以完美运行,问题似乎在于我在哪里接触到 Location 模型。

我的理解是该@results变量应该是一个有效的 ActiveRecord 对象,并且允许我访问关联模型中的数据,在这种情况下是位置?

4

2 回答 2

0

因此,使用 Rubyist 的答案,它可以工作。但是,直到我在 routes.rb 中取消嵌套 Rooms 资源,它才起作用。

我不明白为什么嵌套路由会导致问题。

于 2013-10-29T13:38:05.503 回答
0

就 Sunspot 和 Solr 而言,您所做的任何事情都没有错。

您在视图中的错误是因为您正在调用locationsRoom 对象,而它应该是location(因为 Room 属于 Location)。

错误undefined method location_name for nil是因为您尝试索引的 Room 实例没有关联的位置(即@room.location 为零)。您可以将索引放在条件中(例如。location.location_name if location.present?或使用类似的东西try(例如location.try(:location_name))。

于 2013-10-29T13:46:30.283 回答