可选的rails [英] Rails optional belongs_to

查看:59
本文介绍了可选的rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写用于库存管理的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 。就像您可以想象的那样,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 并使用它来创建产品。但这似乎仍然是黑客。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆