google
yahoo
bing

Archive for the 'web programming' Category

I needed to define a symmetrical habtm relation in my rails app and after searching for a while I found out there’s no option for that. So I came up with my own (dirty?) solution. It works both with MySQL and SQLite.

The migration:


create_table "people" do |t|
t.column :name, :string
end


create_table "people_people_married_with", :id => false do |t|
t.column :source_id, :integer, :null => false
t.column :target_id, :integer, :null => false
end

Add this to the person controller:


has_and_belongs_to_many :married_with, :class_name => "Person",
:join_table => "people_people_married_with", :foreign_key => "source_id",
:association_foreign_key => 'target_id',
:finder_sql => 'SELECT * FROM people INNER JOIN people_people_married_with ON
people.id = people_people_married_with.target_id
WHERE (people_people_married_with.source_id = #{id})
UNION
SELECT * FROM people INNER JOIN people_people_married_with ON
people.id = people_people_married_with.source_id
WHERE (people_people_married_with.target_id = #{id})'

Have fun :)

Close
E-mail It