同时创建两个不同的对象(来自不同的模型)- Rails

Creating two different objects (from different models) at the same time - Rails

我有两个模型:ProductCategory,我想将它们绑定在一起。 假设每个产品都有一个独特的类别,我如何设置 Rails 以在每次用户创建新的 Product 对象时创建(或生成)一个新的 Category 对象?

首先,如果一个类别那么属于一个产品,为什么不把它添加到产品模型中呢?但是如果你坚持你想要的编码方式,你可以利用像 after_create 这样的回调,并在那里编写用于创建类别的代码。这样,无论何时创建产品,都会同时创建一个关联的类别。

class Product < ActiveRecord::Base
  has_one :category
  after_create :create_category

  private
  def create_category
    # code for creating an associated category
  end 
end

注意:大多数时候,我需要在数据库中保存用户的手机号码,并且每个用户都有一个唯一的手机号码 - 所以我没有为手机号码定义一个新模型,而是倾向于拥有它内部用户 table。但是,如果手机号码的信息像运营商名称、国家代码这样扩展——我肯定会把它拆分成一个单独的 table。

    class Product < ActiveRecord::Base
      after_create do
        Category.create product: self
      end
        has_one :category
    end

    class Category < ActiveRecord::Base
      belongs_to :product
    end

并在控制台中

 > a= Product.create
 > a.category
 => #<Category id: 1, product_id: 5, created_at: "2015-11-04 12:53:22", updated_at: "2015-11-04 12:53:22">