我正在为库存管理编写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

推荐答案

您是否有需要用户在场的验证?如果是这样的话,请将其移除.

Ruby-on-rails相关问答推荐

使用turbo流的部分渲染在rails 7中不起作用.

链轮轨道V4链接到外部Ruby 的 list 文件

如何在不触发每次编译的情况下运行`bin/rails测试`?

Ruby - ActiveRecord::ConnectionNotEstablished

如何在我的 rails 应用程序中测试 ActiveRecord::RecordNotFound?

Rails 将 form_for 对象传递给部分

如何使用 capistrano deploy 定位特定的提交 SHA

我如何存根 find_each 以在 rails 3 中进行 rspec 测试

Rails:使用 RSpec 测试命名范围

如何在 Ruby on Rails 中的 cookie 上设置 HttpOnly 标志

Phusion 乘客(适合傻瓜!)

获取磁盘上 ActiveStorage 文件的路径

Rails 范围为 IS NOT NULL 并且不为空/空白?

如何在同一个 Rails 控制器操作中处理多个 HTTP 方法

如何仅使用 PostgreSQL 创建简单的模糊搜索?

如何在 Rails 中设置路由的默认格式?

Dotenv 多行变量

在 Rails 中,在特定时区创建特定时间(不是现在)的最佳方式是什么?

Ruby 安装的 RVM 不工作?

Rails:如何在rails中使用dependent::destroy?