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!

Community
  • 1
  • 1
Andrew
  • 42,517
  • 51
  • 181
  • 281

2 Answers2

7
Photo.joins(:land_uses).where('land_uses.name' => ['foo', 'bar', 'baz'])
Pablo B.
  • 1,823
  • 1
  • 17
  • 27
  • Do you know what the difference between `joins` and `includes` is? – Andrew Apr 05 '11 at 17:17
  • 2
    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. – Pablo B. Apr 05 '11 at 17:25
1

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

Zepplock
  • 28,655
  • 4
  • 35
  • 50
  • Oh, ok so that's the table name not the model name... still learning, but this helps, thanks! – Andrew Apr 05 '11 at 17:17