Ruby on rails 在CRUD期间创建关联rails

Ruby on rails 在CRUD期间创建关联rails,ruby-on-rails,crud,Ruby On Rails,Crud,我有一个有关联的模型。如何在模型上执行CRUD操作时创建/更新关联 就是我跑的时候, @v1_seller = V1::Seller.new(seller_params) @v1_seller.save 它应该保存关联。 我应该在创建钩子并传递参数之后再创建吗(但是我必须在更新中执行同样的操作)?还是我遗漏了什么?我觉得它应该在rails中自动完成 目前我正在明确地这样做: @v1_seller = V1::Seller.new(seller_params) if @v1_seller.sav

我有一个有关联的模型。如何在模型上执行CRUD操作时创建/更新关联

就是我跑的时候,

@v1_seller = V1::Seller.new(seller_params)
@v1_seller.save
它应该保存关联。 我应该在创建钩子并传递参数之后再创建吗(但是我必须在更新中执行同样的操作)?还是我遗漏了什么?我觉得它应该在rails中自动完成

目前我正在明确地这样做:

@v1_seller = V1::Seller.new(seller_params)
if @v1_seller.save
   @v1_seller.assign_categories(params)
我的卖家型号:

class V1::Seller < ActiveRecord::Base
  has_many :categories, :class_name => 'V1::Category', dependent: :delete_all
  has_many :category_names, :class_name => 'V1::CategoryName', through: :categories

  # right now I am manually calling this after a create/update operation in my controller
  def assign_categories(params)
    params.require(:seller).require(:categories)
    params.require(:seller).permit(:categories => []).permit(:name, :brands => [])

    self.categories.clear

    params[:seller][:categories].each do |c|

      if c[:brands].nil? || c[:brands].empty?
        next # skip the category if it has no brands associated with it
      end

      category_name = c[:name]
      category = V1::Category.new
      category.category_name = V1::CategoryName.find_by(name: category_name)
      category.seller = self
      category.save
      c[:brands].each do |b|
        begin
          category.brand_names << V1::BrandName.find_by(name: b)
        rescue ActiveRecord::RecordInvalid
          # skip it. May happen if brand is already added to the particular category
        end
      end
    end
  end
end

似乎您需要
嵌套属性


在此处签出文档:

请先显示
V1::Category
model:方法
assign\u categories
用于服务,而不是模型。第二:你为什么要明确分类?只需编写一个方法,将类别与持久化类别合并,并重新创建尚未存在的类别。
class V1::Category < ActiveRecord::Base
  belongs_to :category_name, :class_name => 'V1::CategoryName', inverse_of: :category
  belongs_to :seller, :class_name => 'V1::Seller', inverse_of: :category
  has_many :brands, :class_name => 'V1::Brand', dependent: :delete_all, inverse_of: :category
  has_many :brand_names, :class_name => 'V1::BrandName', through: :brands, inverse_of: :category

  validates :seller, :uniqueness => {:scope => [:category_name, :seller]}
end