Ruby 关于 rails 数据获取问题
Ruby on rails data fetching issue
你好,我是 rails
的新手
我有一个名为 'messages' 的 table,它包含列 current_user__id、to_user_id 和创建时间
我正在尝试构建一个聊天应用程序,不同的用户可以在其中单独聊天,这些消息将以各自的 ID 存储在消息 table 中。
现在为了在屏幕上打印消息。
我遇到了问题
我需要一个查询,以便 current_user__id 和 to_user_id 对话以及 to_user_id 和 current_user__id 对话都按最新创建的时间列出。
我假设您有两个 ActiveModel:用户和消息。确保您 类 喜欢:
class User < ApplicationRecord
has_many :messages
end
class Message < ApplicationRecord
belongs_to :current_user, class_name: 'User', foreign_key: 'current_user_id'
belongs_to :to_user, class_name: 'User', foreign_key: 'to_user_id'
end
将 t.timestamps
添加到迁移时的一个小问题,它会为您创建 created_at
和 updated_at
字段。
现在我将为您硬编码原始 sql 查询:
def get_messages(current_user_id, to_user_id)
@messages = Message.where(' current_user_id=? OR receiver_user_id=? OR current_user_id=? OR receiver_user_id=? ',
current_user_id, current_user_id, to_user_id, to_user_id).order('created_at DESC')
end
你可以按顺序玩 order('created_at DESC')
如果你只想按升序排列你可以用 ASC 或 order(:created_at)
替换 DESC
您可以设置任何其他查询条件,例如不显示已删除的邮件等。您可以从官方 Ruby 的 Rails 文档了解更多 Active Record Query Interface。
你好,我是 rails
的新手我有一个名为 'messages' 的 table,它包含列 current_user__id、to_user_id 和创建时间
我正在尝试构建一个聊天应用程序,不同的用户可以在其中单独聊天,这些消息将以各自的 ID 存储在消息 table 中。
现在为了在屏幕上打印消息。
我遇到了问题
我需要一个查询,以便 current_user__id 和 to_user_id 对话以及 to_user_id 和 current_user__id 对话都按最新创建的时间列出。
我假设您有两个 ActiveModel:用户和消息。确保您 类 喜欢:
class User < ApplicationRecord
has_many :messages
end
class Message < ApplicationRecord
belongs_to :current_user, class_name: 'User', foreign_key: 'current_user_id'
belongs_to :to_user, class_name: 'User', foreign_key: 'to_user_id'
end
将 t.timestamps
添加到迁移时的一个小问题,它会为您创建 created_at
和 updated_at
字段。
现在我将为您硬编码原始 sql 查询:
def get_messages(current_user_id, to_user_id)
@messages = Message.where(' current_user_id=? OR receiver_user_id=? OR current_user_id=? OR receiver_user_id=? ',
current_user_id, current_user_id, to_user_id, to_user_id).order('created_at DESC')
end
你可以按顺序玩 order('created_at DESC')
如果你只想按升序排列你可以用 ASC 或 order(:created_at)
您可以设置任何其他查询条件,例如不显示已删除的邮件等。您可以从官方 Ruby 的 Rails 文档了解更多 Active Record Query Interface。