I have the following models in Rails 4 with a simple has_many :through association:
class Model < ActiveRecord::Base
has_many :model_options
has_many :options, through: :model_options
end
class Option < ActiveRecord::Base
has_many :model_options
has_many :models, through: :model_options
end
class ModelOption < ActiveRecord::Base
belongs_to :model
belongs_to :option
end
I want to be able to iterate over a Model instance's Options:
model = Model.find.first
model.options.each {}
and access the attributes on the join table.
In Rails 3 you could do this:
class Model < ActiveRecord::Base
has_many :model_options
has_many :options, through: :model_options , select: 'options.*, model_options.*'
end
But select: is deprecated and this produces a deprecation warning.
That said, the SQL generated contains the link table data:
SELECT options.*, model_options.* FROM "options"
INNER JOIN "model_options" ON "options"."id" = "model_options"."option_id"
WHERE "model_options"."model_id" = $1 ORDER BY "options".name ASC [["model_id", 1]]
But the collection returned by AR from model.options removes the link table data.
To remove the deprecations warning in Rails 4, and still produce the same SQL, I did this:
class Model < ActiveRecord::Base
has_many :model_options
has_many :options, -> { select('options.*, model_options.*') }, through: :model_options
end
So, the query is correct, but I am struggling to find the correct way to access the link table data.
I have tried various ways:
model options
model.options.joins(:model_options)
model.options.select('options.*, model_options.*')
model.model_options.joins(:option)
...
None include the join table data.
Thanks.
See Question&Answers more detail:
os