2012-09-26 1 views
0

다음과 같은 모델이 has_many with 조건과 연결되어 있습니다. 레일 has_many : through with : 조건. 연결은 어떻게 만듭니 까?

class User < ActiveRecord::Base 
    has_many :memberships 
    has_many :founded_groups, 
    :through => :memberships, 
    :source => :group, 
    :class_name => 'Group' 
    :conditions => {'memberships.kind' => 'founder'} 
    has_many :joined_groups, ... # same as above, but the kind is 'member' 
end 

class Group < ActiveRecord::Base 
    has_many :memberships 
    has_many :founders, ...  # these two mirror the User's 
    has_many :regular_members, ... # 
end 

class Membership < ActiveRecord::Base 
    validates_presence_of :user_id 
    validates_presence_of :club_id 
    validates_presence_of :kind # <-- attention here! 

    belongs_to :user 
    belongs_to :group 
end 

레일 (적어도 그것에 껍질하지 않습니다) 위의 코드를 좋아하는 것 같다 (Membershipkind 속성의 존재에 대한 유효성을 검사합니다). 그러나 다음이 발생합니다

> user = User.create(...) # valid user 
> club = Club.create(...) # valid club 
> user.founded_clubs = [club] 

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank 

> club.founders << user 

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank 

나는 레일 내 코드의 {'memberships.kind' => 'founder'} 참여하고 연결을 만들 때 사용한다고 가정했지만,이 경우 될 것 같지 않습니다. 따라서 새 회원의 kind은 비어 있으며 오류가 발생합니다.

완전한 고통없이 연결을 쉽게 만들 수 있습니까? 확실히

답변

1

이 작동합니다

> user = User.create(...) # valid user 
> club = Club.create(...) # valid club 
> user.memberships.create(:club_id => club.id, :kind => 'founder') 

는 잘 모르겠어요,하지만이 작동하지 않을 수 있습니다 :

> user.memberships.create(:club => club, :kind => 'founder') 
+0

감사합니다. 하나의 클럽과 2 명의 사용자, 또는 한 명의 사용자와 두 개의 클럽이 여러 요소를 지닌 회원 자격을 만들 수있는 구문을 찾기를 희망했습니다. "많은"부분을 반복하고 연관을 수동으로 만들어야 할 것 같습니다. 오, 그럼. – kikito