我正在为库存管理编写Rails前端.我希望用户能够注册产品,因此我有:
class User < ActiveRecord::Base
has_many :products
# <snip>
end
和
class Product < ActiveRecord::Base
belongs_to :user
# <snip>
end
The problem is that products are created prior to being registered by a user. That is, it's perfectly acceptable to call Product.create
和 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!'
I've thought about a bunch of kludgey workarounds, the most appealing of which is to have a NullUser
subclassing User
和 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
和 later:
class Changeuseridtobeoptionalforproducts < ActiveRecord::Migration
def change
change_column :products, :user_id, :integer, null: true
end
end