2

在我的数据库中,我已将所有外键设置为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 对象的任何查询?

4

2 回答 2

0

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

belongs_to :bar, :conditions => "id != 0"
于 2012-08-22T22:05:21.817 回答
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
于 2012-08-22T20:57:21.417 回答