2009-05-20 1 views
6

저는 피드와 게시물의 두 엔터티간에 has_many 관계가 있습니다. 또한 특정 유형의 게시물, 비디오 및 사진이 있습니다. 이는 단일 테이블 상속을 사용하여 데이터베이스에 구조화됩니다.has_many 및 단일 테이블 상속

은 지금은 내 피드 모델은

class Feed < ActiveRecord::Base 
    has_many :posts 
    has_many :photos 
    has_many :videos 

이를 지정하는 더 나은,보다 전통적인 방법이 있나요 (하위 유형 포함) 피드 게시물 사이에 has_many 관계를 지정했다? 아니면 얻을 수있는만큼 간단합니까?

답변

4

내가 올바르게 이해하면 게시물과 게시물이 비디오 또는 사진이 될 수 있습니다. Jaryl이 말한 것처럼 아마도 이해하기 쉽습니다. 그러나 당신이 단일 테이블 상속이나 polymophic 연관을 사용할 수있는 것을 원한다면 다루는 것이 가장 쉽습니다.

STI - 예 (애자일 웹 개발에서 레일과 3 판) 그래서 당신은 당신이 다음 사람을 통해 찾을 수 있습니다

Customer.create(:name => 'John Doe', :email => '[email protected]', :balance => 78.29) 

고객을 만들 경우

create_table :people, :force => true do |t| 
    t.string :type 

    #common attributes 
    t.string :name 
    t.string :email 

    #attributes for type=Customer 
    t.decimal :balance, :precision => 10, :scale => 2 

    #attributes for type=Employee 
    t.integer :reports_to 
    t.integer :dept 

    #attributes for type=Manager 
    #none 
end 

class Person < ActiveRecord::Base 
end 

class Customer < Person 
end 

class Employee < Person 
    belongs_to :boss, :class_name => "Manager", :foreign_key => :reports_to 
end 

class Manager < Person 
end 

x = Person.find_by_name('John Doe') 
x.class #=> Customer 
x.email #=> [email protected] 
x.balance #=> 78.29 
x.some_customer_class_method # will work because the Person.find method returned a Customer object 

할 수 있으니

class Post < ActiveRecord::Base 
end 
class Photo < Post 
end 
class Video < Post 
end 

다음은 Post.all에 의해 그들 모두를 찾을 수 있지만,

이를 잊지 마세요 (당신은 사진이나 동영상하지 않은 게시물이 경우 포스트 객체)는 사진 및 비디오 객체를 다시 얻을 것 문자열 : db 테이블에 입력하십시오.

+1

http://stackoverflow.com/questions/3231889/rails-sti-with-inheriting-children 저는 STI 자식 개체를 갖는 방법을 알아 내려고하고 있습니다. 따라서 주어진 예제에서는 어떻게 " Person belongs_to : company "및"Company has_many : persons "? – Rabbott

1

이것은 거의 당신이 할 수있는 가장 간단한 것입니다.

음, 사진을 비디오와 동일하게 처리 할 수 ​​있다면 STI를 없애고 명명 된 범위를 사용하여 다양한 유형의 컨텐츠에 접근자를 제공 할 수 있습니다.

0

본인의 질문에 대한 예제는 매우 간단합니다. 이미 STI를 사용 중이며 연관성을 분명하게 명시합니다.

또한 피드 모델의 코드를 1 비트 변경하지 않고 나중에 STI를 추출하여 사진 : 동영상을 별도의 테이블로 분리 할 수 ​​있습니다. 점수!