Vitalii
Vitalii

Reputation: 1812

Trouble with includes

I need to build a query to select records by two criteria (two models): Branch(id) and Plan(created_at)

I tried following queries:

@branches = Branch.where(id: 2).includes(:plans).where("created_at > ?", 1.week.ago)
@branches = Branch.where(id: 2).includes(:plans).where(plans: { "created_at > ?", 1.week.ago })
@branches = Branch.includes(:plans).where(branches: { id: 2 }, plans: { "created_at > ?", 1.week.ago })

I have an error

syntax error, unexpected '}', expecting keyword_end ... "created_at > ?", 1.week.ago })

How can I fix it?

Upvotes: 1

Views: 32

Answers (3)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

Just from reading your code, the problem is with incorrect syntax of your hash:

{ "created_at > ?", 1.week.ago }

Which should be an array:

[ "created_at > ?", 1.week.ago ]

But for your use case, I think you need something like:

@branches = Branch.where(id: 2)
                  .joins(:plans)
                  .includes(:plans)
                  .where("plans.created_at > ?", 1.week.ago)

In order to be able to use a Plan's column created_at, includes is not enough - in that case the error will be thrown of unknown plans. This is why you need to specify joins to properly build whole query.

Hope that helps!

Good luck!

Upvotes: 1

jon snow
jon snow

Reputation: 3072

May this works for you,

Branch.includes(:plans).where(["id = ? and plans.created_at > ?", 2, 1.week.ago])

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

{ "created_at > ?", 1.week.ago } isn't correct hash syntax, it should be in an array:

[ 'created_at > ?', 1.week.ago ]

Upvotes: 1

Related Questions