5

activerecord를 사용하는 로컬 사용자 모델이 있습니다. 사용자에게 전자 메일 필드가 있습니다. 나는 또한 submires 사용자 이메일 주소를 저장하는 created_by 필드를 가진 tasks라는 activeresource 모델을 가지고있다. 나는이 둘을 연결하고 싶지만 올바른 구문이나 심지어 그것이 가능한지에 대해서 고심하고있다.외래 키를 사용하여 activerecord와 activeresource 간의 관계를 정의하는 방법은 무엇입니까?

ActiveResource의 메인 브랜치는 외래 키를 지원하지 않는 것으로 보입니다. alternative branch을 찾았지만 계속 작동하지 못했습니다.

class User < ActiveRecord::Base 
    has_many :tasks 
end 

class Task < ActiveResource::Base 
    belongs_to :user 
    schema do 
    string 'created_by' #email 
    # other fields 
    end 
end 

답변

1

당신은 할 수 없지만 접근 방법을 직접 구현하여 위장 할 수는 있습니다.

class User < ActiveRecord::Base 
    #has_many :tasks 
    def tasks 
    Task.find(:all, params: {created_by: email}) 
    end 
end 

class Task < ActiveResource::Base 
    #belongs_to :user 
    def user 
    User.where(email: created_by).first 
    end 

    schema do 
    string 'created_by' #email 
    # other fields 
    end 
end 

는 당신의 객체 (즉 User.first.tasks.length를) 인 것처럼 코드 을 작성할 수 있습니다. 그러나 실제로 결합되지는 않습니다. 즉, User.first.tasks을 호출하면 데이터베이스에 충돌 한 다음 추가 HTTP 요청을 만들어 작업을 검색합니다. 코드 구조에 따라 예기치 않은 성능 문제가 발생할 수 있습니다.

또한, (이 두 개의 분리 된 데이터 저장소를 이후) 사용자 관련된 모든 작업을 얻을 수있는 단일 쿼리를 실행할 수 없습니다, 당신은 User.joins(:tasks).where({tasks: field_1: true})처럼 멋진 물건을 할 수 없습니다.

4
귀하의 코드가 잘 당신이 Taskuser_id 속성이 외부 키의 역할을하도록, 또는 다음과 같이 User 모델 협회에서 외래 키를 지정할 수 있습니다 주어진 작업을해야

:

class User < ActiveRecord::Base 
    has_many :tasks, foreign_key: "uid" 
end 

을 지금 문제는 belongs_toActiveResource에 사용할 수 없으므로 Task 클래스의 인스턴스에서 user을 검색해야하는 경우가 아니면 제거하고 관계의 다른 쪽은 여전히 ​​작동하지만 필요한 경우 user을 검색하면 자체 구현해야합니다. 파인더 방법은 다음과 같이 당신이 ActiveRecord 모델에 기대하는 것처럼 대신 다음과 같이 belongs_to을 추가 할 ActiveResource 모듈을 확장 할 수 있도록

class Task < ActiveResource::Base 
    schema do 
    string 'created_by' #email 
    # other fields 
    end 

    def user 
    @user ||= User.find self.user_id # use the attribute name that represents the foreign key 
    end 

    def user=(user) 
    @user = user 
    self.update_attribute(:user_id, user.id) 
    end 
end 

이 기본적으로 여러 단체가있는 경우 그러나이 무심 할 수 있으며, 동일하게 동작합니다 :

이렇게하면 ActiveResource 모델에서 belongs_to를 사용할 수 있습니다.

PS : 작업을 위해 : 위의 솔루션은 https://stackoverflow.com/a/8844932/3770684

+0

난 당신이 제안 원숭이 패치와 함께이 시도하지만 실행할 때 'User.last.tasks'나는 '정의되지 않은 메서드'relation_delegate_class을 NoMethodError을'얻을 영감을받은 클래스 ' – Simmo

+0

어떤 버전의 루비와 레일을 사용하고 있습니까? – cousine

+0

Rails 4.1.0 and Ruby 2.1.1 – Simmo