Rails 3 HABTM find by record associated model attribute
Asked Answered
A

2

6

I think this is really basic but I'm horrible with SQL so I have no idea how to do it...

I have a standard HABTM relationship between two models, LandUse and Photo. So I have a land_uses_photos join table, and each model has the standard macro, like:

Photo
has_and_belongs_to_many :land_uses

The land use table has: ID, and Name(string).

I want to find Photos where Land Use Name = 'foo','bar',or 'baz'. How do I do that?

I looked at this question and tried:

Photo.includes(:land_uses).where('land_use.id'=>[6,7])

... but that gave me:

ActiveRecord::StatementInvalid: No attribute named `id` exists for table `land_use`

That's bogus, here's the schema.rb for both LandUse and the join table:

create_table "land_uses", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "display_order"
end

create_table "land_uses_photos", :id => false, :force => true do |t|
  t.integer "land_use_id"
  t.integer "photo_id"
end

So, how do I do this kind of find? And to make it only one question instead of two, how could I find with an "and" condition instead of only an "or" condition?

Thanks!

Acevedo answered 5/4, 2011 at 16:22 Comment(0)
T
7
Photo.joins(:land_uses).where('land_uses.name' => ['foo', 'bar', 'baz'])
Telephonic answered 5/4, 2011 at 16:28 Comment(2)
Do you know what the difference between joins and includes is?Acevedo
Use includes when you want to eager load the association data. This is useful when you want to avoid the N+1 problem. Use joins everywhere else, since it generates a much simpler and faster sql.Telephonic
R
1

you gen an 'id' error since table name is: land_uses and not land_use

Resinous answered 5/4, 2011 at 16:36 Comment(1)
Oh, ok so that's the table name not the model name... still learning, but this helps, thanks!Acevedo

© 2022 - 2024 — McMap. All rights reserved.