0

我有一个 song.rb 模型和一个genre.rb 模型,我希望能够搜索它们。

出于某种原因,Tire 只返回歌曲的搜索结果,而不是流派。

编码:

genre.rb

class Genre < ActiveRecord::Base
  has_many :genre_songs, :dependent => :destroy
  has_many :songs, through: :genre_songs

  include Tire::Model::Search
  include Tire::Model::Callbacks


end

song_controller 片段

def index
    if params[:query].present?
      @songs = Song.search(params[:query], load: true)
    elsif params[:genre]
      @songs = Song.tagged_with(params[:genre]).paginate(:page => params[:page], :per_page => 15)
      get_last_song
    else      
      @songs = Song.order('id').order('plusminus desc nulls last').paginate(:page => params[:page], :per_page => 15) 
      #@songs = Song.tally.paginate(:page => params[:page], :per_page => 15)
      get_last_song
    end
  end

song.rb 片段

include Tire::Model::Search include Tire::Model::Callbacks

index.html.erb 代码段

<%= form_tag songs_path, method: :get do %>
  <p>
    <%= text_field_tag :query, params[:query] %>
    <%= submit_tag "Search", name: nil %>
  </p>
<% end %>
4

1 回答 1

1

在控制器中:

  @songs = Song.search(params)

在歌曲模型中:

  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 15) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?

    end
  end

  def to_indexed_json
    to_json(methods: [:genre_names])
  end

  def genre_names
    genres.map{ |g| g.name}   
  end
于 2013-08-07T08:28:33.483 回答