如何为布尔属性创建方法?

时间:2011-11-24 16:04:31

标签: ruby-on-rails ruby ruby-on-rails-3

如何在方法中将布尔值设置为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

我如何完成此操作以及需要纠正的内容?


更新

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" %>

2 个答案:

答案 0 :(得分:1)

您可能更容易制作一个解释选择的包装器方法,而不是使用直接映射的mutator:

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

然后,您可以在onlineofflineall之间进行选择,或者根据您的偏好进行选择。

编辑:根据要点修改:

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

答案 1 :(得分: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 %>

我将复选框设置为已开始检查两者,以便在线和离线搜索,除非取消选中其中一个。这就是为什么在搜索控制器中我搜索两种方法的参数是否为零。