Query based on a HABTM association
I'm trying to put together a query in ActiveRecord that is in part based on a HABTM association between project
and item
. This is what I'm trying to do:
@project = Project.find(params[:id])
@company = Company.find(params[:cid])
@items = @company.items.where("items.public" => true OR "items.project_ids" => @project.id )
I'm getting all kinds of errors here - first with the OR
, then with the items.project_ids
not being rec开发者_Python百科ognized, etc. How can I write this query properly?
First off, if you are going to use OR, then you'll need to use a string, not hash syntax. Secondly, project_ids is a dynamic field added by Rails - to do the same on a database level, you will have to include the join table and use that.
However, the join table is not a recognised association in Rails, so I think you will have to specify the join manually.
Something like this should work:
@company.items.joins("left join items_projects on items_projects.item_id = items.id").where("items.public = true OR items_projects.project_id = ?", @project.id)
assuming you are using Rails' standard HABTM table name
精彩评论