Skip to content

Instantly share code, notes, and snippets.

@zporter
Created November 11, 2010 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zporter/672522 to your computer and use it in GitHub Desktop.
Save zporter/672522 to your computer and use it in GitHub Desktop.
Rails model with a many-to-many relationship upon itself
class Product < ActiveRecord::Base
# ... other code
has_and_belongs_to_many :products,
:join_table => "related_products",
:foreign_key => "product_a_id",
:association_foreign_key => "product_b_id",
:finder_sql => 'SELECT DISTINCT products.* FROM products INNER JOIN related_products ON (#{id} = related_products.product_a_id OR #{id} = related_products.product_b_id) WHERE (products.id <> #{id})',
:insert_sql => 'INSERT INTO related_products (product_a_id, product_b_id) VALUES (#{id}, #{record.id})',
:delete_sql => 'DELETE FROM related_products WHERE (product_a_id = #{id} AND product_b_id IN (#{record.id})) OR (product_a_id = #{record.id} AND product_b_id IN (#{id}))',
:validate => false,
:uniq => true
# ... other code
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment