저는 레일 5, 간단한 형태를 사용합니다. 내 애플 리케이션에는 Category 모델이 있고 OnlineProduct 모델이있다. 내가 왜 내 OnlineProduct 협회 테이블에 일부 카테고리를 추가하려는 경우 빈 상태로 유지하고 변경하지 않는지 모르겠다.레일 : 연관 테이블 (has_and_belongs_to_many) 레코드를 저장하지 않습니다.
분류 모델 :
class Category < ApplicationRecord
has_ancestry
has_and_belongs_to_many :internet_products
end
InternetProduct 모델 :
class InternetProduct < ApplicationRecord
belongs_to :user
belongs_to :business
has_and_belongs_to_many :categories
end
InternetProduct 컨트롤러 :
: 카테고리에 관한def new
@internet_product = InternetProduct.new
end
def create
@internet_product = InternetProduct.new(internet_product_params)
respond_to do |format|
if @internet_product.save
format.html { redirect_to @internet_product, notice: 'Internet product was successfully created.' }
format.json { render :show, status: :created, location: @internet_product }
else
format.html { render :new }
format.json { render json: @internet_product.errors, status: :unprocessable_entity }
end
end
end
private:
def internet_product_params
params.require(:internet_product).permit(:name, :description, :mainpic, :terms_of_use,
:real_price, :price_discount, :percent_discount,
:start_date, :expire_date, :couponـlimitation, :slung,
:title, :meta_data, :meta_keyword, :enability, :status,
:like, :free_delivery, :garanty, :waranty, :money_back,
:user_id, :business_id,
categoriesـattributes: [:id, :title])
end
그리고 뷰 일부만
<%= f.association :categories %>
모든 카테고리보기 (양식)에 있지만 목록 중 일부를 선택하면 데이터베이스에 저장하지 않습니다. 레일에서 콘솔 이걸
p = InternetProduct.find(5)
p.categories = Category.find(1,2,3)
이것은 아무 문제없이 데이터베이스에 저장하는데, 어떻게해야합니까? 이것을 읽는 탱크
당신과'OnlineProduct' 조인 테이블? – inye
예. 이것은 내가 가지고있는 것입니다 : 'Categories CategoriesInternetBons
Armanlearn
편집 질문이 마이그레이션을 추가하고이 세 개의 테이블의 테이블 스키마를 추가하면 더 나은. – inye