0

Please help me to avoid this syntax error

I want to select first category with its children.

@categories=Category.where(categories: {id:[1]} && categories: {parent_id:[1]})
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
SreRoR
  • 1,151
  • 1
  • 17
  • 44

2 Answers2

1

Why not just do this?

@categories = Category.where(id: [1], parent_id: [1])

This will give you all the categories with id = 1 AND parent_id = 1. Note that, you don't need the [] unless you want to include array of ids or parents ids. If you want for one id and one parent id only, you can just do this:

@categories = Category.where(id: 1, parent_id: 1)
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • 1
    Thank you it works, i tried this . how to write the same by or condition – SreRoR Sep 28 '15 at 05:27
  • In Rails 5 (which is not released yet, coming soon), we will have a feature where we will be able to chain `or` with `where` clause like this: `@categories = Category.where(id: 1).or(Category.where(parent_id: 1)` But, this is not a part of Rails 4. See this post for some more example: http://stackoverflow.com/questions/32753168/rails-5-activerecord-or-query – K M Rakibul Islam Sep 28 '15 at 05:30
  • If you are on Rails 4.2, then you can try this gem: https://github.com/Eric-Guo/where-or then you will be able to use that feature right now. Or, you can always use SQL to write queries using `OR` – K M Rakibul Islam Sep 28 '15 at 05:32
  • 1
    You can do this way to use `OR`: `Category.where("id = ? OR parent_d = ?", 1, 1)` – K M Rakibul Islam Sep 28 '15 at 05:34
0

Assuming you want to find the Category record with id=1 and parent_id=1 the query should be:

@category = Category.where(id: 1, parent_id: 1).first

sghosh968
  • 591
  • 6
  • 12