2010-11-20 4 views
3

: 그것은 많은 위치를 가지고 있지만 레일 고급 협회

class MyModel < ActiveRecord::Base 
    has_many :locations 
    has_one :location, :class_name => 'Location', :join => "RIGHT JOIN locations ON locations.user_id=mymodels.user_id" 
end 

그래서 MyModel는 각 사용자에 대해 하나 개의 위치를 ​​가질 수 있습니다. 어떻게 정의 할 수 있습니까? 고마워!

답변

4

명명 협회 등 MyModel.first.user.location으로 사용자의 위치를 ​​얻을 수 있습니다 모델 이름의 단수 형태는 혼란 스러울 수 있으며, 또한 메소드 중복이 발생할 수 있습니다. 모범 사례는 제외하고 일반적으로 원시 SQL을 제공 할 필요가 없습니다. 당신의 사건도 예외는 아닙니다.

MyModel도 User에 속한 것처럼 보입니다. 는 SQL을 기반으로 다음과 같은 모델을 Assumeing

게시 됨 : : 그리고 사용자는 다음과 같은 일을 할 수있는 위치와 많은 관계로 하나가 나타납니다

class User < ActiveRecord::Base 
    has_many :my_models 
    has_many :locations 
end 

class Location <ActiveRecord::Base 
    belongs_to :my_model 
    belongs_to :user 
end 



class MyModel < ActiveRecord::Base 
    has_many :locations 
    belongs_to :user 
    has_one :user_location, through => :user, :source => :location 
end 

을하지만, 당신이 모르는 어떤 위치 사용자가 여러 위치에있는 경우 얻을 수 있습니다. 그러나 적어도 하나가 있다면 당신은 하나가 보장됩니다.

2

내가 잘못 될 수도 ...

class MyModel < ActiveRecord::Base 
    has_many :location 
    belongs_to :user 
end 

class Location< ActiveRecord::Base 
    belong_to :my_model 
end 

class User< ActiveRecord::Base 
    has_one :my_model 
end 

당신은 당신이 복수와 모두 연관을 가지고

+1

has_many 연관이 있으므로 어떤 종류의 조인으로 정의 할 수 있어야합니다. 또한 100 개의 결과 목록을 상상해보십시오. 데이터베이스에 대한 요청은 1 개만 필요합니다. – xpepermint