2016-04-25 48 views
1

如何通過範圍做複選框搜索紅寶石如何使用範圍

我有形式這樣

<% VenueCategory.all.each do |c| %> 
<%= check_box_tag("venue_categories[]", c.id)%> 
<%= c.name%> 
<% end %>` 

我要搜索的場地類別,如果多一種選擇是用寫複選框活動記錄搜索選擇。如何使用範圍做

我想這樣 在我property.rb模型

scope :venue_category, -> (venue_categories_id) { where venue_category_ids: venue_categories }

控制器:

@properties = Property.where(:status=>'1') @properties = @properties.venue_categories(params[:venue_categories]) if params[:venue_categories].present?

模型venuecategory.rb

class VenueCategory < ActiveRecord::Base belongs_to :property end

property.rb

class Property < ActiveRecord::Base has_and_belongs_to_many :venue_categories end

我得到錯誤,當我嘗試這樣做。

我不知道如何使用範圍進行多個複選框選項搜索。如果有人知道,請幫助我。

任何幫助是可觀的。

+0

你有什麼錯誤? –

+0

@Anthony E未定義的方法'venue_categories'的# SreRoR

+0

現在我改變了控制器像這樣@properties = @ properties.venue_category if params [:venue_categories] .present?'那麼​​我得到這個錯誤在我的屬性模型'參數錯誤(0爲1)' – SreRoR

回答

2

將範圍想象成一個函數,名稱爲venue_categories,它接受參數 - venue_categories - 場地類別ID數組。

scope :venue_categories, -> (venue_categories) { where(id: venue_categories) } 

這裏id是要匹配的字段名稱。

控制器

@properties = Property.where(status: '1') 
@properties = @properties.venue_categories(params[:venue_categories]) if params[:venue_categories].present? 

這應該工作。

+0

@Senbin爲此獲得這樣的查詢。 'SELECT'properties'。* FROM'properties' WHERE'properties'.'status' ='1'AND'properties'.'id' IN(1,2,3,4,7,8)' – SreRoR

+0

@sree對不起,我不清楚你想要什麼。你能澄清一下嗎? – Sebin

+0

而不是獲取properties.ids我需要venue_categories'.'id' IN(1,2,3,4,7,8) – SreRoR