2012-08-28 3 views
4

사용자 및 조직에 조인 모델 UsersOrganisation이 있습니다. 사용자는 조직의 관리자 일 수 있습니다. 그렇다면 is_admin 부울이 참입니다.레일 has_many through with 조건, 새로 빌드

데이터베이스에서 is_admin 부울을 수동으로 설정하면 Organisations.admins가 예상대로 작동합니다.

콘솔에서 나는 Organisation.first.users << User.first을 수행 할 수 있으며 예상대로 organisations_users 항목을 만듭니다.

그러나 내가 수행 할 경우 Organisation.first.admins << User.last은 관리자가 아닌 일반 사용자를 만듭니다. 즉, 조인 테이블의 is_admin 부울이 올바르게 설정되지 않았습니다.

직접 조인 테이블에 항목을 만드는 것 외에 다른 작업을 수행하는 좋은 방법이 있습니까?

class User < ActiveRecord::Base 

    has_many :organisations_users 
    has_many :organisations, :through => :organisations_users 

end 

class Organisation < ActiveRecord::Base 

    has_many :organisations_users 
    has_many :users, :through => :organisations_users 
    has_many :admins, :through => :organisations_users, :class_name => "User", 
      :source => :user, 
      :conditions => {:organisations_users => {:is_admin => true}} 

end 

class OrganisationsUser < ActiveRecord::Base 

    belongs_to :organisation 
    belongs_to :user 

end 
+0

그것을'has_many 확인 : 관리자가, : => ... ... 통해 '실제로 선택을 위해 작동합니다, 데이터를 삽입하는 것이 아닙니다. 따라서'Organisation.first.admin << User.last'를 실행하면 정상적인 항목 만 생성됩니다. 그러나,임이 같은 방법으로 궁금합니다. 귀하의 질문에 Thnx. – Samiron

답변

2

:

class Organisation < ActiveRecord::Base 

    has_many :organisations_users 
    has_many :organisations_admins, :class_name => "OrganisationsUser", :conditions => { :is_admin => true } 

    has_many :users, :through => :organisations_users 
    has_many :admins, :through => :organisations_admins, :source => :user 

end 
+0

Organisation.first.admins.create (: user => User.first)' – Edward

+0

조직 모델에서 작은 별칭을 만들면 가능합니다 (편집 된 답변 참조) – sled

+0

끝났습니다. 최대 조인 테이블에 대한 중첩 된 양식을 만드는,하지만 난 내 질문에 매우 명확하게 대답이 답변을 수락했습니다. – Edward

1

다음은 조직 모델에 대한 코드입니다. has_many :through<< 연산자 일부 왜곡이 있습니다

has_many :admins do 

    def <<(user) 
    user.is_admin = true 
    self << user 
    end 

end 

가 (코드가 확인되지 않은)

+0

할당 문제를 해결하기 때문에이 방법을 더 선호합니다. – Midnighter

5

당신은 항상 협회의 < < 방법을 대체 할 수 있습니다. 하지만 당신은 @ 에레즈 대답처럼 그것을 과부하시킬 수 있습니다.

이 내 접근 (I는 구성원에 OrganisationsUsers 이름) 범위를 사용

:

class User < ActiveRecord::Base 

    has_many :memberships 
    has_many :organisations, :through => :memberships 

end 

class Organisation < ActiveRecord::Base 
    has_many :memberships 
    has_many :members, :through => :memberships, :class_name => 'User', :source => :user 

    # response to comment: 
    def admins 
    memberships.admin 
    end 
end 

class Memberships < ActiveRecord::Base 

    belongs_to :organisation 
    belongs_to :user 

    scope :admin, where(:is_admin => true) 
end 

지금 나는이 같은 새 관리자를 만들기 :

Organisation.first.memberships.admin.create(:user => User.first) 

내가이 범위에 대해 좋아하는 것은 당신이다 멤버십 클래스에서 "멤버쉽의 종류"를 정의하면 조직 자체가 멤버십의 종류에 전혀 신경을 쓸 필요가 없습니다.

업데이트 :

지금 당신이 할 수있는

Organisation.first.admins.create(:user => User.first)