有没有办法阻止ActiveRecord查询id = 0的对象?

时间:2012-08-22 20:50:59

标签: ruby-on-rails activerecord

在我的数据库中,我将所有外键设置为unsigned int not null default 0。因此,在我的Rails应用程序中,我收到了很多关于id = 0的对象的查询。这是一个例子:

class Foo < ActiveRecord::Base
  belongs_to :bar
end

class Bar < ActiveRecord::Base
end

在控制台中,如果我这样做:

Foo.new.bar

然后运行此查询:

SELECT `bars`.* FROM `bars` WHERE `bars`.`id` = 0 LIMIT 1

我尝试过猴子修补但是method_missing似乎无法捕获这些类型的调用。我真的不想(不能真的在这一点上)改变我的架构。我可以解决这个问题的唯一方法是手动总是检查bar_id!= 0,但这似乎不太干净。

思想/建议?

只是为了澄清,我不想更改架构。问题是:可以配置/攻击ActiveRecord,使得0和nil都被视为无效ID,从而阻止对id = 0的对象进行任何查询吗?

2 个答案:

答案 0 :(得分:0)

无论如何,我正在发布迁移解决方案。如果

,我会很乐意删除它
  

...此时无法真正改变我的架构

显示为真。在新的迁移文件中:

def up
  change_column_default(:bars, :id, nil) # removes default, letting it be null
  execute "update bars set id = null where id = 0"
end

def down
  change_column_default(:bars, :id, 0)
  execute "update bars set id = 0 where id is null"
end

答案 1 :(得分:0)

您可以尝试使用belongs方法中的条件。条件创建一个默认的where子句,必须通过任何活动的记录查询来满足。

belongs_to :bar, :conditions => "id != 0"
相关问题