2009-08-14 19 views
0

はこれを考えてみましょうお気に入りモデル)簡単な表関係

ありがとうございます!追加favorite_articles

答えて

1

あなたはユーザーからのお気に入りの記事を取得するためにhas_many :through関連付けを使用することができます。私はあなたが望んでいた右のものを理解している場合

+0

それは、ありがとう! –

+0

aha +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

私は自分のアンカーにあなたが望むものを含めるように編集しました。これはうまくいくはずです – marcgg