Rails 可选的belongs_to [英] Rails optional belongs_to
问题描述
我正在编写用于库存管理的 Rails 前端.我希望用户能够注册产品,所以我有:
I'm writing a Rails frontend for inventory management. I want users to be able to register products, so I have:
class User < ActiveRecord::Base
has_many :products
# <snip>
end
和
class Product < ActiveRecord::Base
belongs_to :user
# <snip>
end
问题在于产品是在用户注册之前创建的.也就是说,调用 Product.create
并让它将 user_id
设置为 nil
是完全可以接受的.但是,正如您所想象的,Rails 并不支持这种开箱即用的功能:
The problem is that products are created prior to being registered by a user. That is, it's perfectly acceptable to call Product.create
and just have it set the user_id
to nil
. As you can imagine, though, Rails doesn't support this out of the box:
> Product.create!
(0.3ms) SELECT COUNT(*) FROM "products" WHERE "products"."type" IN ('Product')
(0.1ms) begin transaction
(0.1ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: User can't be blank
from ~/.rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/validations.rb:56:in `save!'
我想过很多笨拙的变通方法,其中最吸引人的是让 NullUser
子类化 User
并使用它来创建产品.但这似乎仍然是一个黑客.这有什么 Rails 方式?
I've thought about a bunch of kludgey workarounds, the most appealing of which is to have a NullUser
subclassing User
and use that to create products. But that still seems like a hack. What's the Rails Way with this?
谢谢.
相关迁移:
class AddUseridToProducts < ActiveRecord::Migration
def change
add_column :products, :user_id, :integer
end
end
及以后:
class Changeuseridtobeoptionalforproducts < ActiveRecord::Migration
def change
change_column :products, :user_id, :integer, null: true
end
end
推荐答案
您是否有需要用户在场的验证?如果是这样,请将其删除.
Do you have a validation that requires user be present? If so, remove that.
这篇关于Rails 可选的belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!