Rails Scoping For has_many :through To Access Extra Data

后端 未结 1 667
感动是毒
感动是毒 2020-12-01 23:28

As we know, in rails you can add extra attributes to your has_many :through join model

I\'d like to extract the extra data from the join model & pop

相关标签:
1条回答
  • 2020-12-02 00:02

    I actually found the solution to this

    The magic lies in the SQL SELECT statement, which I managed to find out about on this RailsCast

    Specifically, alongside the standard SELECT * FROM table, you can define another function, and attach it to the original query with the AS function

    So what I got was this code:

    #Images
        has_many :image_messages, :class_name => 'ImageMessage'
        has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }, :class_name => 'Image', :through => :image_messages, dependent: :destroy
    

    This allows you to attach the "caption" for the image to the Image object, allowing you to call @image.caption -- it works brilliantly!

    0 讨论(0)
提交回复
热议问题