16

저는 레일에 다 대다 관계를 가지고 있습니다. 모든 데이터베이스 테이블의 이름은 적절하고 적절하게 지정됩니다. 모든 모델 파일은 복수형이며 별도의 단어에 밑줄을 사용합니다. 모든 명명 규칙은 루비 및 레일 표준을 따릅니다. 나는 내 모델에서 이렇게 많이 사용하고있다.UserController의 ActiveRecord :: HasManyThroughAssociationNotFoundError # 환영합니다.

has_many :users, :through => :users_posts #Post model 
has_many :posts, :through => :users_posts #User model 
belongs_to :users #UsersSource model 
belongs_to :posts #UsersSource model 

이 오류의 원인은 무엇입니까? has_many :through를 사용하는 경우

ActiveRecord::HasManyThroughAssociationNotFoundError in UsersController#welcome Could not find the association :users_posts in model Post

+0

: http://stackoverflow.com/questions/944126/rails-has 그냥 간단한 테이블에 가입하려면

, 그것은 이전 HABTM 구문을 사용하는 것이 더 쉽습니다 - 만나는 문제 – 18bytes

답변

36

당신은 별도의 연결로 모델을 조인을 정의 할 필요가 : 당신이 가입 모델 자체, 또는 경우에 관한 데이터를 유지해야 할 때

class Post < ActiveRecord::Base 
    has_many :user_posts 
    has_many :users, :through => :user_posts 
end 

class User < ActiveRecord::Base 
    has_many :user_posts 
    has_many :posts, :through => :user_posts 
end 

class UserPost < ActiveRecord::Base 
    belongs_to :user # foreign_key is user_id 
    belongs_to :post # foreign_key is post_id 
end 

이 가장 잘 작동합니다 다른 두 모델과 분리 된 조인에 대해 유효성 검사를 수행하려고합니다. 정확히 같은 문제에 대해 해결

class User < ActiveRecord::Base 
    has_and_belongs_to_many :posts 
end 

class Post < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end