DonMB
DonMB

Reputation: 2718

rails access records from a sub related model

Simple task which I don't know an answer to:

I have 3 models: Topic, Page and Subpage

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

I look for the topic, based on the URL slug:

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

Now I want to access all subpages that are related to topics, so in fact I want to "skip" the pages.

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

How does that query look like?

Thanks for any help.

Upvotes: 2

Views: 58

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

You can declare your relations with a 'through':

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

Then includes it and put a condition on it:

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

In your case:

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

For the record, you have to use the relation's name in the .includes() & .joins() methods, and we use the plural in the where clause (to match the table's name):

IF user belongs_to :post

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

IF user has_many :posts

User.includes(:posts).where(posts: { title: 'Post #1' })
                 #^^ Plural because has_many :posts

Upvotes: 2

Related Questions