2011-11-24 67 views
0

如何在方法中將布爾值設置爲false?如何爲布爾屬性創建方法?

對於我BusinessStore搜索我試圖讓3個不同的單選按鈕從網上商店離線商店所有分店選擇。

這是我BusinessStore模式和3種方法我試圖做出單選按鈕:

attr_accessible :online_store # boolean attribute 

def online_search 
    business_store.online_store = true 
end 

def offline_search 
    business_store.online_store = false 
end 

def all_search 
    # Give all results whether true or false 
end 

如何完成這一點,需要加以糾正呢?


UPDATE

Product.rb 

def search_type=(boolean) 
    case (boolean) 
    when 'online' 
     @online_search = true 
     @offline_search = false 
    when 'offline' 
     @online_search = false 
     @offline_search = true 
    when 'all' 
     @online_search = true 
     @offline_search = true 
    else 
    @online_search = true 
    @offline_search = true 
    end 
end 

search/index.html.erb 

<%= label_tag :search_type, "All" %> 
    <%= radio_button_tag :search_type, "all" %> 
<%= label_tag :search_type, "Online" %> 
    <%= radio_button_tag :search_type, "online" %> 
<%= label_tag :search_type, "Offline" %> 
    <%= radio_button_tag :search_type, "offline" %> 

回答

0

採取不同的辦法來代替,而只是做兩個複選框:

SearchController.rb

def index 
    @search = Product.search do 
    q.with(:online_search, params[:online_search] == 1) if params[:online_search].nil? 
    q.with(:offline_search, params[:offline_search] == 0) if params[:offline_search].nil? 
    end 
    @products = @search.results 
end 

搜索/ index.html.erb

<%= label_tag :online_search, 'Online' %> 
    <%= check_box_tag :online_search, params[:online_search], true %> 
    <%= label_tag :offline_search, 'Offline' %> 
    <%= check_box_tag :offline_search, params[:offline_search], true %> 

我將複選框設置爲已開始檢查兩者,以便在線和離線搜索,除非其中一個未選中。這就是爲什麼在搜索控制器中,我搜索參數是否爲兩種方法的參數。

1

你可能有一個更容易的時間進行解譯選擇,而不必直接映射存取器的包裝方法:

def search_method=(value) 
    case (value) 
    when 'online' 
    @online_search = true 
    @offline_search = false 
    when 'offline' 
    @online_search = false 
    @offline_search = true 
    else 
    @online_search = true 
    @offline_search = true 
    end 
end 

def online_search? 
    @online_search 
end 

def offline_search? 
    @offline_search 
end 

然後你在online,offlineall之間進行選擇,或者選擇其他默認值河

編輯:修正基於要點:

def index 
    @search = Product.search do 
    fulltext params[:search] 
    paginate(:per_page => 10, :page => params[:page]) 
    order_by(:purchase_date, :desc) 
    order_by(:price,:asc) 

    includes(:business_store) 
    where(:business_store => { :online_store => true }) 
    end 
    @products = @search.results 
end 
+0

對不起,我是在軌道上的紅寶石,什麼是包裝方法?另外,使用'business_store.online_store = false'作爲在線商店= false正確? – LearningRoR

+0

包裝器方法是通過應用一些抽象封裝簡單操作的方法的通用編程術語。我認爲你必須設置在線和離線,但不只是其中之一。 – tadman

+0

這對我來說是令人困惑的,因爲我無法真正瞭解如何使用該方法設置控制器或視圖。有其他方法嗎? – LearningRoR