0

저는 레일 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) 

이것은 아무 문제없이 데이터베이스에 저장하는데, 어떻게해야합니까? 이것을 읽는 탱크

+0

당신과'OnlineProduct' 조인 테이블? – inye

+0

예. 이것은 내가 가지고있는 것입니다 : 'Categories CategoriesInternetBons Armanlearn

+0

편집 질문이 마이그레이션을 추가하고이 세 개의 테이블의 테이블 스키마를 추가하면 더 나은. – inye

답변

0

해결책을 찾았습니다. 때 당신은 또한 할 새로운 예를 들면 관련 방법에 컨트롤러에

accepts_nested_attributes_for :categories 

또한 중첩 형식에 대해이 명령을 추가해야합니다 모델에, simple_form에서 선택한 모음을 사용하려는 경우 우리는 has_and_belong_to_many 또는 기타 관계를 사용 우리는해야만합니다

def new 
    @internet_product = InternetProduct.new 
    @internet_product.categories.build 
end