2009-08-14 2 views
0

이를 고려간단한 테이블 관계

class User < ActiveRecord::Base 
    # name, email, password 
end 

class Article < ActiveRecord::Base 
    # user_id, title, text 
end 

class Favorites < ActiveRecord::Base 
    # user_id, article_id 
end 

어떻게 내가에서 마음에 드는 제품 (user.articles (사용자가 만든 기사) @ 및 user.favorite_articles @ 가질 수있는 방법으로 모두 함께이를 배치해야합니까 좋아하는 모델)

미리 감사드립니다! 추가 favorite_articles

답변

1

당신은 사용자의 마음에 드는 기사를 가져 오기 위해 has_many :through 연결을 사용할 수 있습니다 : 나는 당신이 원하는 옳은 일을 이해하면

+0

그게 다야, 고마워! –

+0

아하 +1, 당신이 나를 이길 :) – marcgg

1

, 나는

class User < ActiveRecord::Base 
    has_many :articles 
    has_many :favorite_articles, :through => :favorites, :source => :article 
end 

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :user 
end 

class Favorites < ActiveRecord::Base 
    has_and_belongs_to_many :user 
    has_one :article 
end 

편집 말 것. 또한 특정 기사를 선호하는 사용자를 가져 오는 데 사용할 수도 있습니다.

class User < ActiveRecord::Base 
    has_many :articles 
    has_many :favorites 
    has_many :favorite_articles, :through => :favorites, :source => :article 
end 

class Article < ActiveRecord::Base 
    belongs_to :user 
    has_many :favorites 
    has_many :favorited_by_users, :through => :favorites, :source => :user 
end 

class Favorite < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :user 
end 
+0

문제는 기사 개체 대신 즐겨 찾기 개체로 끝납니다. Rails를 사용하는 간단한 방법이 있다는 것을 알고 있지만 완전히 잊어 버렸습니다. 어쩌면 users_videos 테이블을 가지고 has_many : through를 사용하는 것에 관한 것이었지만 확실하지 않습니다. 어떤 생각? –

+0

내 anwser를 편집하여 원하는 것을 포함 시켰습니다. 이것은 잘 작동합니다. – marcgg