2016-08-26 7 views
-1

最初のサンドボックスアプリケーションを開発したとき、私はリレーショナルテーブル用のレコードをいくつか取得したかったのです。リレーションテーブル上でリレーションレコードを取得する方法

User.rb:

class User < ActiveRecord::Base 
    #has many followed articles 
    has_many :follow_articles 

そしてFollowArticleモデル:

class FollowArticle < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :article 
end 

と記事モデル:

class Item < ActiveRecord::Base 
    has_many :follow_articles 
end 

私はすべて私にあるように、ユーザーの記事を踏襲取得したいです私が持っているコントローラ:

私を与えた

ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_FollowArticle:x3014X2 

私の見解では、私はこれらの記事を反復処理することができます。完璧に動作

<% @articles.each do |article| %> 
     <%= article.article.name %> 
<% end %> 

。記事の代わりfollowArticlesを返すために

@items = current_user.follow_articles 

は私の代わりにFollowArticles配列、のようなものの記事配列を取得するには、この方法でこれを行うことができますか?

答えて

1

has_many :throughを使用してください。 the Guideから

にhas_many:アソシエーション・スルーは、しばしば、他のモデルとの多対多の接続を設定するために使用されます。この関連付けは、第3のモデルを進めることによって、宣言モデルが他のモデルの0個以上のインスタンスと一致し得ることを示す。例えば、患者が医師に診察を依頼する診療を考えてみましょう。関連団体の宣言は次のようになります。だから、

class Physician < ApplicationRecord 
    has_many :appointments 
    has_many :patients, through: :appointments 
    end 

    class Appointment < ApplicationRecord 
    belongs_to :physician 
    belongs_to :patient 
    end 

    class Patient < ApplicationRecord 
    has_many :appointments 
    has_many :physicians, through: :appointments 
    end 

、完全にドットを結ぶ...

#User.rb 
    class User < ActiveRecord::Base 
    has_many :follow_articles 
    has_many :followed_articles, through: :follow_articles 
    end 
+0

は、編集用のブリキ男をありがとう! – jvillian

+0

私が以前のhas_many記事を使って現在のユーザーの記事を取得していた場合はどうすればいいですか?またはmetter doesnt metter? –

+0

'has_many:articles'を' has_many:Following_articles'に変更しました。現在、あなたは 'has_many:articles'をどこで使っていますか? – jvillian

関連する問題