Created
November 11, 2010 13:53
-
-
Save zporter/672522 to your computer and use it in GitHub Desktop.
Rails model with a many-to-many relationship upon itself
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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