Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Retrieving attributes through rails join table


I have 3 models: products, tags and products_tags:

Tag model:

class Tag < ActiveRecord::Base
        has_many :products, :through => :products_tags
        has_many :products_tags
end

Product Model:

class Product < ActiveRecord::Base
  has_many :tags, :through => :products_tags
  has_many :products_tags
  accepts_nested_attributes_for :tags
  accepts_nested_attributes_for :products_tags

Join:

class ProductsTag < ActiveRecord::Base
  belongs_to :product
  belongs_to :tag
end

I need a query which will retrieve the attributes related to the tag and the product model, as an AREL object.

So for example:

My tag table has 1 field: Cat_name My product table has: Title, URL, Image_url.

How can I retrieve all these attributes as an AREL record.


Solution

  • You don't state where you want to start your search from to retrieve this, so let's just go through all of them.

    Starting from tags

    Specific tag and associated products as an ActiveRecord object:

    Tag.find(params[:id], include: :products)
    

    Specific tag and associated products as an arel object:

    Tag.where(id: params[:id]).includes(:products)
    

    All tags and associated products as an array of ActiveRecord objects:

    Tag.includes(:products)
    

    All tags and associated products as an arel object:

    Tag.includes(:products).arel
    

    Starting from products

    Specific product and associated tags as an ActiveRecord object:

    Product.find(params[:id], include: :tags)
    

    Specific product and associated tags as an arel object:

    Product.where(id: params[:id]).includes(:tags)
    

    All products and associated tags as an array of ActiveRecord objects:

    Product.includes(:tags)
    

    All products and associated tags as an arel object:

    Product.includes(:tags).arel
    

    Rails has an excellent guide that covers many to many associations and joins.