2010-02-09 2 views
5

has_manythrough 연관에서 find_or_create_by을 사용하는 동안 문제가 발생합니다. I는 User 객체에 연관 rolesfind_or_create_by를 호출 할 때`has_many``through` 연관에 find_or_create_by를 사용하는 중 오류가 발생했습니다.

class Permission < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :role 
end 

class Role < ActiveRecord::Base 
    # DB columns: user_id, role_id 

    has_many :permissions 
    has_many :users, :through => :permissions 
end 

class User 
    has_many :permissions 
    has_many :roles, :through => :permissions 
end 

레일 에러가 발생.

unless u.roles.exists?(:rolename => "admin") 
    u.roles << Role.find_or_create_by_rolename("admin") 
end 

나는 찾을 궁금 경우 has_manythrough 협회와 find_or_create_by 작품 :

u = User.first 
u.roles.find_or_create_by_rolename("admin") 

# Rails throws the following error 
# NoMethodError: undefined method `user_id=' for #<Role id: nil, rolename: nil, 
# created_at: nil, updated_at: nil> 

나는 다음과 같이 내 코드를 변경하여 문제를 해결 할 수 있었다.

답변

1

작동하지만, :through과는 작동하지 않습니다.

+0

예, 문제는 다음을 통해 제한됩니다. 이를 반영하기 위해 질문을 업데이트 할 것입니다. –

+0

나는이 질문에 대해 더 이상 대답하지 않을 것이라고 생각합니다. 'find_or _...'메소드는': through' 연관을 가지고 동작하지 않습니다. 'Permission' 모델을 삭제하고 간단한 매핑 테이블과 함께'has_and_belongs_to_many' 관계를 사용하는 것이 유일한 방법입니다. –

+0

'u.roles.find_by_rolename ("admin")'과 같은 호출은'has_many : through'와 작동합니다. 그래서 나는'u.roles.find_or_create_by_rolename ("admin")'이 효과가있을 것이라고 생각했다. 이 경고가 명시된 문서를 가르쳐 주시겠습니까? –

관련 문제