簡體   English   中英

Ruby on Rails搜索2個模型

[英]Ruby on Rails search 2 models

是的...我花了3天的時間自己嘗試,不花錢。

我有2個稱為電影和放映廳的模型。 場次屬於電影,場次有很多場次。

電影具有某些屬性(:title,:date_of_release,:description,:genre)。

篩選具有以下屬性(:start_time,:date_being_screened,:film_id(電影的外鍵))。

我想做的就是針對這兩種模型創建一個Search。 我想做這樣的事情...

@films = Film.advanced_search(params [:genre],params [:title],params [:start_time],params [:date_showing])

然后在電影模型中...

def self.advanced_search(genre, title, start_time, date)
    search_string = "%" + title + "%"

    self.find(:all, :conditions => ["title LIKE ? OR genre = ? OR start_time LIKE ? OR date_showing = ?", title, genre, start_time, date], order: 'title')
    end
end 

我認為這樣做不可能如此,但是我希望我的解釋足夠詳細,以便任何人都可以理解im TRYING要做的事情?? :-/

謝謝大家的幫助

我會將搜索功能提取到一個單獨的(非ActiveRecord)類中,例如AdvancedSearch因為它不能很好地適合FilmScreening類。

除了編寫復雜的SQL查詢,您還可以先搜索電影,然后放映電影,然后組合結果,例如:

class AdvancedSearch
  def self.search
    film_matches = Film.advanced_search(...) # return an Array of Film objects
    screening_matches = Screening.advanced_search(...) # return an Array of Screening objects

    # combine the results
    results = film_matches + screening_matches.map(&:film)

    results.uniq # may be necessary to remove duplicates
  end
end

更新資料

假設您的高級搜索表單有兩個字段-類型和位置。 因此,當您提交表單時,發送的參數為:

{ :genre => 'Comedy', :location => 'London' }

您的控制器將類似於:

def advanced_search(params)
  film_matches = Film.advanced_search(:genre => params[:genre])
  screening_matches = Screening.advanced_search(:location => params[:location])

  # remaining code as above 
end

也就是說,您正在拆分參數,將每個參數發送到不同的模型以運行搜索,然后組合結果。

本質上,這是一個OR匹配-它會返回與該流派匹配的電影或正在指定場地放映的電影。 (如果需要和AND匹配,則需要計算出數組的交集)。

我想寫點東西,但是這個演員表顯示了所有http://railscasts.com/episodes/111-advanced-search-form

與您的情況幾乎相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM