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
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!