开发者

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 sch开发者_Python百科ema.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'])


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜