在CRUD期间创建关联rails

时间:2014-12-11 06:44:09

标签: ruby-on-rails crud

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

也就是说,当我跑

@v1_seller = V1::Seller.new(seller_params)
@v1_seller.save

它应该保存关联。 我应该创建after_create钩子并传递params(但是我必须在更新时做同样的事情)?或者我错过了什么?我觉得它应该在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::Cateogry模型:

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

1 个答案:

答案 0 :(得分:0)

好像你需要nested attributes

在此处查看文档:{​​{3}}