0

두 가지 모델 User 및 Category가 있습니다. 다음 코드를HABTM의 조인 테이블에 특성을 추가하고 연결 값을 가져올 때이를 가져 오는 방법은 무엇입니까?

class User < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    accepts_nested_attributes_for :categories, :allow_destroy => true 
    alias_method :categories=, :categories_attributes= 
end 

이를 이미 카테고리 테이블에 존재하지 않을 때 나는 카테고리를 만들

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

을 고려하십시오. 카테고리가 테이블에 이미있는 경우 카테고리의 ID를 조인 테이블의 사용자로 참조해야합니다. 그리고 참조 유형과 함께 조인 테이블에 필드 say type을 추가해야 할 필요가 있다고 생각합니다.

말 예를 들어

user table: 

1, sample_user 
2, test_user 

category table: 

1, category1 
2, category2 

categories_users: 

category_id    user_id  type 
     1      1   type1 
     2      1   type2 
     1      2   type2 
     1      2   type1 

그리고 사용자의 범주를 가져올 때 난의 종류에 따라 분류 개체를 얻을 필요 category 객체 내의 category.

어떻게하면됩니까? 제발 도와주세요

+0

가능한 중복 http://stackoverflow.com/questions/18575039/ :이 경우

, 그 같은 것을 얻을 것이다 how-can-i-use-accepts-nested-attributes-with-habtm) – gabrielhilal

답변

2

HABTM 연결에서 조인 테이블의 특성을 원한다면 조인 테이블을 별도의 모델로 만들고 대신 has_many :through을 사용해야합니다.

class User < ActiveRecord::Base 
    has_many :categories, through: :user_categories 
end 

class Category < ActiveRecord::Base 
    has_many :users, through: :user_categories 
end 

class UserCategory < ActiveRecord::Base # or whatever you want to call it 
    belongs_to :user 
    belongs_to :category 
end 
[? 내가 HABTM와 속성을 중첩 수락 사용 방법]의 (
+0

확인. 그리고 중첩 된 속성은 어떻습니까? 카테고리 테이블에 추가하고 HABTM에서와 같이 user_categories 테이블에서 자동으로 참조 할 수 있습니까? 또한 범주를 이미있는 경우 범주 id를 참조로 사용할 수있는 방법을 알고 싶습니다. 또한 참조가 자동으로 저장된 것처럼 추가 특성을 조인 테이블에 추가 할 수 있습니다. – logesh

+0

중첩 된 속성에 대해서는 accepts_nested_attributes_for를 사용할 수 있습니다. 아마 그걸 살펴봐야 할 것입니다. – Frost

+0

나는 "accepts_nested_attributes_for : categories"를 사용할 수 있다고 생각하지만 참조는 자체적으로 user_categories 테이블에 저장 될 것이고 범주에 대한 데이터를 보낼 때 조인 테이블의 추가 속성에 값을 추가하는 방법을 알려주시겠습니까? – logesh

관련 문제