3

has_and_belongs_to_many 연관을 사용하여 다 대다 관계를 갖는 두 개의 모델, 아이템 및 카테고리가 있습니다. 내 모델에서레일에 대해 혼란 스럽다 has_and_belongs_to_many Association

나는

class Item < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :items 
end 

이 나는 ​​조인 테이블 "categories_items"생성 :

create_table "categories_items", :id => false, :force => true do |t| 
    t.integer "category_id" 
    t.integer "item_id" 
end 

내가 오류를받지 못했습니다,하지만 난 그 협회가 허락하는 것에 대해 정확히 혼란 스럽네요. 나는 몇 가지 범주 @category이있는 경우 지금, 나는

@item.categories 
을 수행하여

@category.items 
나는 주어진 항목 @item과 관련된 카테고리를 찾을 수 있다고 가정

를 수행하여 모든 항목을 찾을 수 있습니다

내가 ActiveModel :: MissingAttributeError을 말한다 오류 얻을 그러나 :없는 속성 : 카테고리

내가 오해 오전하는 방법, 또는 내가 내 코드에서 뭔가를 has_and_belongs_to_many 협회 기능 놓친 거지? 고맙습니다!

편집 - 추가 정보 :

나는 혼란 내가 항목/카테고리를 할당하기로되어있어 방법에있다 생각합니다. 현재, 내가 독립적으로 만드는거야 : 다음

@item = Item.new 
... add attributes ... 
@item.save 

@category = Category.new 
... add attributes ... 
@category.save 

@category.items << @item 
@item.categories << @category 
+0

당신이 여기에있는 것은 괜찮아 보이고 협회는 두 가지 방법으로 작동해야합니다. '@ item'은 어떻게 할당됩니까? – x1a4

+0

나는 테스트 프로젝트 (레일즈 3.2.1)에 코드를 붙여 넣었고 협회는 두 가지면에서 모두 잘 돌아갔다. –

+3

일반적으로 Model.select ("something"). first.somethingelse를 수행하면 MissingAttribute 예외가 발생합니다. 실행중인 코드와 백 트레이스를 git에 붙여 넣을 수 있습니까? – bcd

답변

0

로를 연결 나는 당신이 전에 한 번 겪고있는 무슨 경험했던 생각 . 혼란이 다른 테이블을 통해 연결하는 방법에 있다고 생각합니다. 다음에서는 한 사용자가 많은 기술을 가질 수 있습니다. 기술은 또한 많은 사용자에게 연결됩니다. 이것과 비슷한 것이^_^

class User < ActiveRecord::Base 
    has_many :skills_users 
    has_many :skills, through: :skills_users 

class SkillsUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :skill 

class Skill < ActiveRecord::Base 
    has_many :skills_users 
    has_many :users, through: :skills_users 
관련 문제