Rails查询Array是否包含另一个Array

时间:2013-03-03 21:27:38

标签: ruby-on-rails model where

我有一个Filter类,我用它来过滤转租列表。在我的过滤器类中,我有一个Listing方法,它返回符合用户在表单中输入的条件的所有列表。这是过滤器类。

class Filter < ActiveRecord::Base

  attr_accessible :air_conditioning, :available_rooms, :bathrooms, :furnished, :negotiable, :new, :parking, :maximum_price, :private_bathroom, :show, :term, :total_rooms, :utilities, :washer_dryer
  serialize :term

  def listings
    @listings ||=find_listings
  end

private

    def find_listings
    listings=Listing.order(:price)
    listings=listings.where("listings.price <= ?", maximum_price) if maximum_price.present?
    listings=listings.where(total_rooms: total_rooms) if total_rooms.present?
    listings=listings.where(available_rooms: available_rooms) if available_rooms.present?
    listings=listings.where(bathrooms: bathrooms) if bathrooms.present?
    listings=listings.where(term: term)
    listings=listings.where(furnished: furnished)
    listings=listings.where(negotiable: negotiable)
    listings=listings.where(utilities: utilities)
    listings=listings.where(air_conditioning: air_conditioning)
    listings=listings.where(parking: parking)
    listings=listings.where(washer_dryer: washer_dryer)
    listings=listings.where(private_bathroom: private_bathroom)
    listings
  end

 end

问题在于行

listings=listings.where(term: term)

术语保存为可序列化的字符串。 Aka ['Summer','Fall]用户选中复选框以选择转租可用的条款。但是,where子句每次都失败。如何检查用户选择的元素是否包含在列表的条款中?

1 个答案:

答案 0 :(得分:0)

我不确定你打算用term来做什么,但是你能把它变成一个字符串类型然后使用这样的东西吗?

TERMS = %w(Spring Summer Fall Winter)
validates :term, :inclusion => { :in => TERMS }
编辑:另外,您是否打算让Filter实际上是数据库中的表,或者只是具有验证的模型?如果是后者,您可能需要考虑使用ActiveModel:http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/