Elegantly selecting attributes from has_many :through join models in Rails

前端 未结 4 628
春和景丽
春和景丽 2021-02-06 14:51

I\'m wondering what the easiest/most elegant way of selecting attributes from join models in has_many :through associations is.

Lets say we have Items, Catalogs, and Cat

相关标签:
4条回答
  • 2021-02-06 14:56

    You should be able to do @catalog.catalog_item.position if you provide the other end of the association.

    class Catalog < ActiveRecord::Base
      belongs_to :catalog_item
    end
    

    Now you can do Catalog.first.catalog_item.position.

    0 讨论(0)
  • 2021-02-06 15:03

    You can do something like this:

    # which is basically same as your "frustrating way" of doing it
    @item.catalog_items.find_by_catalogue_id(@item.catalogs.first.id).position
    

    Or you can wrap it into in an instance method of the Item model:

    def position_in_first_catalogue
      self.catalog_items.find_by_catalogue_id(self.catalogs.first.id).position
    end
    

    and then just call it like this:

    @item.position_in_first_catalogue
    
    0 讨论(0)
  • 2021-02-06 15:08

    Why don't You just

    @item = Item.find(4)
    position = @item.catalog_items.first.position
    

    why do you go through catalogs? It doesn't make any sense to me since you are looking for first ANY catalog!?

    0 讨论(0)
  • 2021-02-06 15:10

    Just adding answer so that it might help others

    CatalogItem.joins(:item, :catalog).
      where(items: { id: 4 }).pluck(:position).first
    
    0 讨论(0)
提交回复
热议问题