Retactoring advanced has_many example
Posted
by atmorell
on Stack Overflow
See other posts from Stack Overflow
or by atmorell
Published on 2010-03-13T11:46:48Z
Indexed on
2010/03/13
11:55 UTC
Read the original article
Hit count: 380
ruby-on-rails
|rails
Hello,
My user model has three relations for the same message model, and is using raw SQL :/ Is there a better more rails way to achieve the same result?
Could the foreign key be changed dynamically? e.g User.messages.sent (foreign key = author_id) and User.messages.received (foreign key = recipient ) I have been trying to move some of the logic into scopes in the message model, but the user.id is not available from the message model...
Any thoughts?
Table layout:
create_table "messages", :force => true do |t|
t.string "subject"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "author_id"
t.integer "recipient_id"
t.boolean "author_deleted", :default => false
t.boolean "recipient_deleted", :default => false
end
This is my relations for my user model:
has_many :messages_received, :foreign_key => "recipient_id", :class_name => "Message", :conditions => ['recipient_deleted = ?', false]
has_many :messages_sent, :foreign_key => "author_id", :class_name => "Message", :conditions => ['author_deleted = ?', false]
has_many :messages_deleted, :class_name => "Message", :finder_sql => 'SELECT * FROM Messages WHERE
author_id = #{self.id} AND author_deleted = true OR
recipient_id = #{self.id} AND recipient_deleted = true'
Best regards. Asbjørn Morell
© Stack Overflow or respective owner