I need to build app with user messages (dialogs).
I’ve solved this problem by this way:
app/models/conversation.rb
class Conversation < ActiveRecord::Base
belongs_to :user
belongs_to :interlocutor
has_many :messages
end
app/models/message.rb
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
attr_accessible :message
end
app/models/user.rb
class User < ActiveRecord::Base
...
def conversations
Conversation.uniq.joins(:messages)
.where("conversations.user_id = ?", self.id)
.where("conversations.interlocutor_id = ?", self.id)
.order("messages.created_at DESC")
end
end
I’m confused by conversations method. It’s like PHP way – no flexibility.
Can it be rewrited by rails way? Maybe it can be AR relationship?
Thanks.
Consider scoping the query.
In Rails 3, this would look something like
Use it like this: