【问题标题】:Sunspot model assocation太阳黑子模型协会
【发布时间】:2013-01-25 16:02:56
【问题描述】:

我有两个模型,一个School 模型和Price 模型。每个学校都有价格。我想返回搜索结果学校及其价格。我正在使用导轨和太阳黑子。

学校管理员:

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

学校模型:

class School < ActiveRecord::Base
 has_many :prices
 # sunspot search
  searchable do
   text :name, :locality
  end
end

索引 - 视图

<% 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 %>

如何为每所学校返回其价格,包括黑子?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 sunspot sunspot-rails


    【解决方案1】:

    也许您可以使用 :include 进行预加载:

    @search = School.search(:include => :prices) do # or :include => :price, depends on the relation
     fulltext params[:search]
     paginate :page => params[:page], :per_page => 7
    end
    

    补充:

    如果学校只能有一个价格,您应该在学校模型中将has_many :prices 替换为has_one :price。完成此操作后,您可以通过以下方式访问您想要的价格:result.price.min(看看number_to_currency,您可能对这个Helper感兴趣)

    【讨论】:

    • 它与这个 ":include => :prices" 一起工作,但它返回的价格结果如下:#<0x007fa381b9fd30>
    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多