code_junkie

Elegantly selecting attributes from has_many :through join models in Rails

Nov 13th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. class Item < ActiveRecord::Base
  2. has_many :catalog_items
  3. has_many :catalogs, :through => :catalog_items
  4. end
  5.  
  6. @item = Item.find(4)
  7. @catalog = @item.catalogs.first
  8. @cat_item = @item.catalog_items.first(:conditions => {:catalog_id => @catalog.id})
  9. position = @cat_item.position
  10.  
  11. class Item < ActiveRecord::Base
  12. has_many :catalog_items
  13. has_many :catalogs, :through => :catalog_items, :select => "catalogue_items.position, catalogs.*"
  14. end
  15.  
  16. # which is basically same as your "frustrating way" of doing it
  17. @item.catalog_items.find_by_catalogue_id(@item.catalogs.first.id).position
  18.  
  19. def position_in_first_catalogue
  20. self.catalog_items.find_by_catalogue_id(self.catalogs.first.id).position
  21. end
  22.  
  23. @item.position_in_first_catalogue
  24.  
  25. class Catalog < ActiveRecord::Base
  26. belongs_to :catalog_item
  27. end
  28.  
  29. @item = Item.find(4)
  30. position = @item.catalog_items.first.position
Add Comment
Please, Sign In to add comment