2

答えがわからない単純なタスク:

トピック、ページ、サブページの 3 つのモデルがあります。

topics   has_many pages
pages    has_many subpages
pages    belongs_to topics
subpages belongs_to pages

URL スラッグに基づいてトピックを探します。

@topic = Topic.find_by_slug(params[:topic])

ここで、トピックに関連するすべてのサブページにアクセスしたいので、実際にはページを「スキップ」したいと考えています。

@subpages = Subpage.where(topic => @topic)

そのクエリはどのように見えますか?

助けてくれてありがとう。

4

1 に答える 1

2

「スルー」を使用して関係を宣言できます。

Subpage
  belongs_to :page
  has_one :topic, through: :page

Page
  has_many :subpages
  belongs_to :topic

Topic
  has_many :pages
  has_many :subpages, through: :pages

次に、それを含めて条件を付けます。

Subpage.includes(:topic).where(topics: { title: 'Hello World!' })

あなたの場合

@subpages = Subpage.includes(:topic).where(topics: { id: @topic.id })

record.includes()の場合、 &メソッドでリレーションの名前を使用する必要が.joins()あり、where 句で複数形を使用します (テーブルの名前と一致させるため):

IF ユーザーの所属先 :post

User.includes(:post).where(posts: { title: 'Post #1' })
                 #^ No plural #^ Always use the plural in the where clause

IF ユーザー has_many :posts

User.includes(:posts).where(posts: { title: 'Post #1' })
                 #^^ Plural because has_many :posts
于 2013-11-05T19:42:43.077 に答える