2013-12-14 2 views
0

데이터베이스에서 정보를 검색하기위한 하나의 객체 지향적 인 방법은 함께 연결된 3 가지 방법을 사용하는 것입니다.self.class.where는 데이터베이스에서 정보를 어떻게 검색합니까?

def "find_friend" 
    self.class.where({friend_id: user_id}) 
end 

을 다음과 같이 호출 :

이 같은 인스턴스 메서드를 만들 수 있습니다

| id | friend_id | user_id | 

| 1 | 1   | 3  | 
| 2 | 2   | 1  | 
| 3 | 3   | 2  | 
:

# @user_friendship == <UserFriendship id: 1, friend_id: 2, user_id: 1> 

@user_friendship.find_friend 

을 우리는이 같은 user_friendships 테이블이있는 경우

그러면 find_friend 메소드는 두 번째 레코드를 반환합니다 (id가 2 인 레코드)

@user_friendship.find_friend #=> <UserFriendship id: 2, friend_id: 2, user_id: 1> 

지금 제 첫 번째로 정확한 것은 무엇입니까?

둘째, 어떻게 실제로 작동합니까? self.class.inspect 단순히 모델 테이블의 스키마의 해시로 보이는 반환

self.class.inspect #=> `UserFriendship(id: integer, friend_id: integer, user_id: integer)` 

그래서 어떻게이 간단한 해시에 대한 쿼리를 실행할 수 있습니까?

self.class.where({friend_id: user_id}) 

답변

0

어디에서와 마찬가지로 호출 할 수있는 클래스 메소드입니다.

UserFriendship.where({friend_id: user_id}) 

모든 루비 객체는 자신의 클래스 형이 너무 self.class.where({friend_id: user_id})이 같은 일을 알고있다. self.classUserFriendship으로 바뀌면 key 값 쌍의 해시를 전달하는 where 메소드를 호출하여 필요한 레코드를 되돌릴 수 있습니다.

관련 문제