0
연관이있는 모델이 있습니다. 모델에서 CRUD 작업이 수행 될 때 연결을 생성/업데이트하는 방법. 내가CRUD 중 연관 레일 만들기
@v1_seller = V1::Seller.new(seller_params)
@v1_seller.save
그것은 협회를 저장해야 실행할 때,
. after_create 후크를 만들고 매개 변수를 전달해야합니까 (그렇다면 업데이트에서 동일한 작업을 수행해야합니까?). 또는 나는 무엇인가 놓치고 있냐? 나는 그것이 레일에서 자동으로 이루어져야한다고 생각한다.
현재 내가 명시 적으로 그 일을하고있다 :@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
모델을 : 당신이 nested attributes
이 필요한 것처럼
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
보여주십시오 'V1 : 처음에 Category' 모델 –
: 방법'assign_categories'이 아닌 모델에 대한 서비스입니다. 두 번째 : 카테고리를 정리하면 무엇입니까? 카테고리를 지속 된 메소드와 병합하는 메소드를 작성하고 아직 존재하지 않는 카테고리를 다시 작성하십시오. –