0

基本上,在我的应用程序中,一首歌有很多类别,一个类别有很多歌曲,通过一个称为分类的连接模型。

我在歌曲模型中基本上有一个搜索功能,目前看起来像这样:

def self.search(search)
    if search
      find(:all, conditions: ['title LIKE ?', "%#{search}%"], order: 'title')
      find(:all, conditions: ['lyrics LIKE ?', "%#{search}%"], order: 'title')
    else
      #if nothing is inputed then just show all songs
      find(:all, order: 'title')
    end
  end

这很好用,因为标题和歌词是歌曲模型的一部分。但是,我不确定如何添加一个函数,以便您可以输入类别描述(类别模型具有的唯一属性)并让它在搜索结果中也返回它,因为它位于单独的模型。提前感谢您的帮助!

4

1 回答 1

1

使用 ActiveRecord包含方法。

 class Song < ActiveRecord::Base
   has_many :categorizations
   has_many :categories, :through=>:categorizations

   def self.search(search)
    res=includes(:categories).order('title')
    res=res.where('title LIKE :search OR lyrics LIKE :search',:search=>"%#{search}%") if search
    res
  end

  def self.search_by_category_desc(search)
    res=joins(:categories).order('title')
    res=res.where('categories.description LIKE ?',"%#{search}%") if search
    res
  end

  def self.search_by_title_or_lirics_or_cat_desc(search)
    res=includes(:categories).order('title')
    res=res.where('title LIKE :search OR categories.description LIKE :search OR lyrics LIKE :search',:search=>"%#{search}%") if search
    res
  end
 end

这将预加载搜索歌曲的所有类别。

记住joinsand之间的区别includesActiveRecord 查询中的“includes”和“joins”有什么区别?

于 2012-07-19T10:16:23.800 回答