Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 HABTM find by record associated model attribute

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!

like image 684
Andrew Avatar asked Apr 05 '11 16:04

Andrew


2 Answers

Photo.joins(:land_uses).where('land_uses.name' => ['foo', 'bar', 'baz'])
like image 60
Pablo B. Avatar answered Sep 26 '22 01:09

Pablo B.


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

like image 37
Zepplock Avatar answered Sep 25 '22 01:09

Zepplock