开发者

How to query a joined table (has_and_belongs_to_many) in a controller

开发者 https://www.devze.com 2023-01-09 20:59 出处:网络
I have established a relation between project.rb and keyword.rb using has_and_belongs_to_many. I now want to query in my projects-controller all projects linked to a certain keyword. What is the easi

I have established a relation between project.rb and keyword.rb using has_and_belongs_to_many. I now want to query in my projects-controller all projects linked to a certain keyword. What is the easiest way to query the joined table keywords_projects? Where is the connector from pr开发者_C百科ojects.rb to the joined table?

@projects = Project.find(:all, :conditions => [??])

Any help is much appreciated. Thx.


Easy way:

@projects = Keyword.find('keyword').projects

or:

@projects = Project.all(:conditions => {:keywords => {:name => 'keyword'}}, :include => :keywords)


Ok, it seems something's wrong in my Rails app then:

In both my models (here Folder and Role), I have habtm's defined (:roles, :folders). CRUD works, the folders_roles table exists so the DB is populated flawlessly. But when trying to query ...

@folders = Role.where("name = ?", "family").folders

... in my folder's controller, Rails barks about ...

undefined method `folders' for #<ActiveRecord::Relation:0xb6ecc12c>

(I simply want to load only those folders, that are associated with the role called "family".)

0

精彩评论

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