2011-01-04 8 views
1

이 질문은 거의 대답하지만 여전히 과도하다고 생각합니다. Trouble with Rails has_many relationships레일에서 여러 개의 일대 다 관계 만들기

는 정말 그냥이 같은해야 할 과제가

@user.browsing_location = location1 
@user.home_location = location2 

내가 주변에 인터넷 검색을 많이 해봤 모든 정보가 모순, 또는 많은 관계로 많은 설정을 설명하고 지정하려면 중개 테이블을 사용하는 방법을 설명합니다. 하지만 실제로 필요한 모든 데이터베이스는 사용자 테이블이 위치에 대해 서로 다른 이름의 ID 필드를 갖도록해야합니다. 다음과 같은 일이있을 것입니까?

사용자 클래스

class User < ActiveRecord::Base 
    #locations created by this user 
    has_many :locations, :foreign_key => :creator_id 

    #locations for browsing and visiting 
    belongs_to :browsing_location, :source => :location 
    belongs_to :home_location, :source => :location 

end 

위치 클래스

class Location < ActiveRecord::Base 
    #Users who are just browsing this location now 
    has_many :browsing_users, :foreign_key => :browsing_location_id, :source => :users 
    #Users who are living here now 
    has_many :home_users, :foreign_key => :home_location_id, :source => :users 

    #User who created this location 
    has_one :user 
end 

이 같은 관계가 필요합니다 내 모델의 꽤 많은 그래서 이것에 대한 별도의 테이블을 생성하는 것을 피하기하고 싶습니다.

답변

0

browsing_location 및 home_location이라는 위치 클래스와 browsing_user 및 home_user라는 사용자 클래스를 상속하는 두 개의 테이블을 상속받는 두 개의 테이블이있는 것으로 보입니다. Rails 3의 경우 :

당신은 일반적인 생각을 가지고 있습니다 만, 약간 혼란스러워 보입니다. : 소스는 많은 관계에서 사용할 연관을 결정하기 위해 사용됩니다. 대신에 필요한 것 : class_name

foreign_key 속성을 올바르게 사용하려면 사용자 및 위치에 대한 테이블 정의를 확인해야합니다.

user.rb 

class User < ActiveRecord::Base 
    # locations created by this user 
    has_many :locations, :foreign_key => :creator_id 

    # I'm assuming the locations belong to the user, as you're end goal was stated as 
    # the ability to call set user.browsing_location and user.home_location 
    # that would mean that browsing_location and home_location would need to belong to 
    # the User class, not the other way around. 
    has_many :browsing_locations, :class_name => :location 
    has_many :home_locations, :class_name => :location 

end 

class Location < ActiveRecord::Base 

    # User who created the location 
    belongs_to :user 

    # Users who are just browsing this location now 
    has_many :browsing_users, :class_name => :users 
    # Users who are living here now 
    has_many :home_users, :class_name => :users 

end 
+0

감사합니다. 이것이 내가 필요한 것이라고 생각합니다. 지금 해보려고. 우리가 has_many와 has_many의 역 관계를 가지고 있기 때문에 활성 레코드가 추가 테이블을 생성하기 위해 마술을하고 있습니다. 아니면 내 테이블 정의를보고 모든 것을 올바르게 설정했는지 확인해야한다는 것입니다. –

+0

Location에 속한 클래스는 User 유형이지만 기술적으로 User 클래스는 아니므로 사용자가 만든 has_many 관계는 기술적으로 서로 바뀌지 않습니다. 그렇지 않으면 many to many 관계가 생기고 has_many : through 또는 has_and_belongs_to_many 관계를 수행해야합니다. –

+0

foreign_key 정의를 확인하기 위해 테이블 ​​정의를보고 싶었습니다. 일반적으로 foreign_key를 정의 할 필요는 없지만 올바르게 수행하고있는 것처럼 보입니다. –