Rails 3 HABTM find by attribute related record

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

I have a standard HABTM connection between two models, LandUse and Photo. Therefore, I have a land_uses_photos connection table, and each model has a standard macro, for example:

Photo has_and_belongs_to_many :land_uses 

The land use table has: ID and name (row).

I want to find "Photos" where "Land Use" is "foo", "bar" or "baz". How to do it?

I looked through this question and tried:

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

... but it gave me:

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

This is fake, here is schema.rb for LandUse and 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? And to solve only one question instead of two, how can I find with the condition "and" instead of "or" conditions?

Thanks!

+6
sql ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many
source share
2 answers
 Photo.joins(:land_uses).where('land_uses.name' => ['foo', 'bar', 'baz']) 
+7
source share

you are generating an 'id' error because the table name is: land_uses and not land_use

+1
source share

All Articles