简体   繁体   中英

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!

Photo.joins(:land_uses).where('land_uses.name' => ['foo', 'bar', 'baz'])

你生成'id'错误,因为表名是: land_uses而不是land_use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM