Rails 请教一下,Rails 没有使用数据库层面进行数据完整性验证的吗?

scige · 2012年11月18日 · 2159 次阅读

写一下示例代码,商品和类别是一对多的关系

class Product < ActiveRecord::Base
  belongs_to :category
  attr_accessible :name
  validates :category_id, presence: true
end

class Category < ActiveRecord::Base
  has_many :products
  attr_accessible :name
end

设置 Category 只有 1~4,这里新建 Product 的类别是 10,期望应该是失败的

p = Product.new
p.category_id = 10
p.save

上面的代码竟然会成功! 查了一下 Rails Guides,加上了验证,也是无效

belongs_to :category, :validate => true

Rails 的完整性验证应该会让上面的创建失败吧,为何没有生效呢? 难道 Rails 提供的完整性验证是程序层面的而没有使用数据库层面的外键进行验证? 或者是我的用法不对,请教大家,谢谢!

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号