Ruby on rails Rails方式用户对话
我需要建立应用程序与用户消息(对话框)。 我通过以下方式解决了这个问题: app/models/conversation.rbRuby on rails Rails方式用户对话,ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Activerecord,Ruby On Rails 3.1,我需要建立应用程序与用户消息(对话框)。 我通过以下方式解决了这个问题: app/models/conversation.rb class Conversation < ActiveRecord::Base belongs_to :user belongs_to :interlocutor has_many :messages end class Message < ActiveRecord::Base belongs_to :conversation belo
class Conversation < ActiveRecord::Base
belongs_to :user
belongs_to :interlocutor
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
attr_accessible :message
end
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
类对话
app/models/message.rb
class Conversation < ActiveRecord::Base
belongs_to :user
belongs_to :interlocutor
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
attr_accessible :message
end
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
class消息
app/models/user.rb
class Conversation < ActiveRecord::Base
belongs_to :user
belongs_to :interlocutor
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
attr_accessible :message
end
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
class用户
我被对话方法弄糊涂了。这就像PHP的方式——没有灵活性
可以用rails的方式重写吗?也许这可能是一种关系
谢谢。为什么一个
用户
没有很多对话
?这对我来说是最有意义的
class User < ActiveRecord::Base
...
has_many :conversations
end
class用户
另外,您已经说过
对话属于用户!您没有完成关系的另一半…为什么用户没有很多对话?这对我来说是最有意义的
class User < ActiveRecord::Base
...
has_many :conversations
end
class用户
另外,您已经说过对话属于用户!您没有完成关系的另一半…请考虑查询
在Rails 3中,这看起来像
class Conversation < ActiveRecord::Base
scope :involving, lambda do |user|
joins(:messages)
.where("conversations.user_id = ?", user.id)
.where("conversations.interlocutor_id = ?", user.id)
.order("messages.created_at DESC")
end
end
考虑一下这个查询
在Rails 3中,这看起来像
class Conversation < ActiveRecord::Base
scope :involving, lambda do |user|
joins(:messages)
.where("conversations.user_id = ?", user.id)
.where("conversations.interlocutor_id = ?", user.id)
.order("messages.created_at DESC")
end
end
对话的外键可以是用户id或对话者id(用户id是开始对话的用户的id,对话者id是对话的对话者的id)。所以我需要合并用户的所有对话(这意味着无论谁开始了对话,结果都是如此)。。另外,我也不确定我是否正确地翻译了母语中的“对话者”一词。意思是“对话的另一个成员”:)对话的外键可以是用户id或对话者id(用户id是开始对话的用户的id,对话者id是对话的对话者的id)。所以我需要合并用户的所有对话(这意味着无论谁开始了对话,结果都是如此)。。另外,我也不确定我是否正确地翻译了母语中的“对话者”一词。意思是“对话的另一个成员”: