我正在为库存管理写一个Rails前端.我希望用户能够注册产品,所以我有:
class User < ActiveRecord::Base has_many :products # <snip> end
和
class Product < ActiveRecord::Base belongs_to :user # <snip> end
问题是产品是在用户注册之前创建的.也就是说,完全可以调用Product.create,并将其设置为nil.尽管如此,您可以想像,Rails不支持这一点:
> 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!'
我已经想到了一堆kludgey的解决方法,最有吸引力的是有一个NullUser子类化用户并使用它来创建产品.但这似乎还是一个黑客.这是什么Rails方式?
谢谢.
相关迁移:
class AddUseridToProducts < ActiveRecord::Migration def change add_column :products,:user_id,:integer end end
然后:
class Changeuseridtobeoptionalforproducts < ActiveRecord::Migration def change change_column :products,:integer,null: true end end