0

현재 사용자, 딜러 및 역할 모델을 연결하는 설정이 있습니다. User와 Dealer는 many to many이고, Dealer_user 할당 테이블로 예상대로 작동합니다.레일 3/활성 레코드 - 할당 테이블의 추가 모델 관련 문제

문제는 딜러에게 특정한 역할을 사용자에게 할당하고 싶다는 것입니다. 즉, 한 판매상의 판매 관리자와 부품 관리자가 될 수 있습니다. 다른).

이 작업을 수행하기 위해 저는 Role_type에 속하는 Role 모델을 가지고 있습니다. 역할은 Dealer_user에 속해야하며 Dealer_user에는 많은 역할이 있어야합니다.

내가 할 수있는 것은

dealer.users.where(:id => user.id).first.roles
이고 그 딜러 만의 역할 만 반환한다는 것입니다.

내가 가진 문제는 내가 다음 테스트 코드를 실행할 때이다 :

Cannot modify association 'User#roles' because the source reflection class 'Role' is associated to 'DealerUser' via :has_many.

사람이 내가 (아래에있는) 내 모델 잘못하고있는 무슨 제안 할 수 있습니다 :

dealer.users.where(:id => user.id).first.roles.create(:role_type_id => 1 + Random.rand(4))

을 나는 오류가?

참고 : Dealer_user와 Role이 가지는 belongs_to 관계는 Sale_user 또는 Dealer와 동일한 기능이 필요한 기타 연결 테이블에도 속할 수 있기 때문에 다형성을 갖습니다.

class Dealer < ActiveRecord::Base 
    attr_accessible :name, :address_id 
    has_many :dealer_users 
    has_many :users, :through => :dealer_users 
    has_many :roles, :through => :dealer_users 
end 

class User < ActiveRecord::Base 
    attr_accessible :first_name, :last_name 
    has_many :dealer_users 
    has_many :dealers, :through => :dealer_users 
    has_many :roles, :through => :dealer_users 
end 

class DealerUser < ActiveRecord::Base 
    attr_accessible :dealer_id, :user_id 
    belongs_to :dealer 
    belongs_to :user 
    has_many :roles, :as => :role_originator 
end 

class Role < ActiveRecord::Base 
    attr_accessible :role_type_id 
    belongs_to :role_type 
    belongs_to :role_originator, :polymorphic => true 
end 

편집 : 아무도 도와 줄 수 있습니까?

답변

1

역할 테이블과의 연관을 has_many through으로 지정합니다. 그런 다음 모델은 다음과 같이 보일 것이다 dealer_user 테이블을 제거하고 역할 테이블 dealer_iduser_id 에 열을 추가 : 쉽게 당신이하려는 쿼리의 유형을 할 수 있도록해야

class Dealer < ActiveRecord::Base 
    has_many :users, :through => :roles 
    has_many :roles 
end 

class User < ActiveRecord::Base 
    has_many :dealers, :through => :roles 
    has_many :roles 
end 

class Role < ActiveRecord::Base 
    belongs_to :dealer 
    belongs_to :user 
end 

합니다. 레일 가이드는 정말 좋은 개요를 가지고 있습니다. here

관련 문제