检查MySQL / Rails中的布尔列是否为true

时间:2010-05-05 21:25:43

标签: mysql ruby-on-rails

Rails和MySQL:

我有一个表有几个代表标签的布尔列的表。我想找到这些列中特定列之一为'true'的所有行(或者我想在MySQL的情况下,'1')。我在视图中有以下代码。

@tag = params[:tag]

@supplies = Supply.find(:all,
  :conditions=>["? IS NOT NULL and ? !=''", @tag, @tag], :order=>'name')

正在从网址传入@tag。那么为什么我得到了所有的@supplies(即每一行),而不仅仅是那些@tag列的真实。

谢谢!

2 个答案:

答案 0 :(得分:1)

如果params[:tag]设置为foo,则find方法会生成此查询:

select * from supplies where 'foo' is not null and 'foo' != '' order by name;

这将返回所有Supply条记录,因为两个条件始终为真。

  1. 'foo' is not null
  2. 'foo' != ''
  3. 当然,您打算将params[:tag]作为列名,但这只是一个糟糕的设计。

    您的tag模型应该有Supply属性并使用以下查找程序:

    @supplies = Supply.all(:conditions => ["tag = ?", params[:tag]], :order => "name")
    

    如果您真的希望供应能够选择多个标签,请使用:

    class Supply < ActiveRecord::Base
      has_and_belongs_to_many :tags
    end
    
    class Tag < ActiveRecord::Base
      has_and_belongs_to_many :supplies
    end
    
    @supplies = Supplies.all(:conditions => {:tags => ['foo', 'bar']}, :order => "name")
    

答案 1 :(得分:-1)

我认为这就是你想要做的事情

@tag = params[:tag]
@supplies = Supply.find(:all, :conditions=>["? = ?", @tag, true], :order=>'name')