首页 > 解决方案 > Rails 向版主或管理员重播消息 - 取决于 created_at 日期

问题描述

我的应用程序目前只显示客户在申请产品后收到的消息。我想让客户能够回复来自版主的原始消息并将其保存在他的收件箱(版主收件箱)中。但是,如果来自版主的原始邮件超过 3 天,则应将邮件发送给管理员并将其保存在他的收件箱(管理员收件箱)中。

该应用程序有 4 个模型:

user.rb

class User < ApplicationRecord
  has_one :inbox
  has_one :outbox
  has_many :messages

  scope :client, -> { where(is_client: true) }
  scope :admin, -> { where(is_admin: true) }
  scope :moderator, -> { where(is_moderator: true) }
end

message.rb

class Message < ApplicationRecord
  belongs_to :inbox
  belongs_to :outbox
end

当用户发送消息时,它会进入他们的发件箱和收件人的收件箱:

inbox.rb

class Inbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end

outbox.rb

class Outbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end

我正在尝试这样的事情:

MessagesController.rb

def show
  @message = Message.find(params[:id])
end

def new
  @message = Message.new
end

def create

  @message = Message.create(
  if current_user.message.created_at > 3.days.ago
    outbox: moderator.outbox
  else
    outbox: admin.outbox
  end
)
end

如果我假设我只有一个版主和一个客户端,我是否应该创建另一个控制器来捕获我想要回复的这条消息?

标签: ruby-on-railsruby

解决方案


假设在用户收件箱中有回复原始邮件的链接

= link_to 'Reply', new_message_path(message_id: orignal_message_id_goes_here)

message_id将作为查询字符串传递

= form_for @message do |f|
  = hidden_field_tag :original_message_id, params[:message_id]
  ...

这将提交original_message_id表单数据

def create
  orignal_message = current_user.inbox.messages.find_by(id: params[:original_message_id])

  inbox = if orignal_message.created_at > 3.days.ago 
             orignal_message.moderator.inbox
          else
             # find admin and get inbox
          end

  @message = Message.create(
    inbox: inbox
    body: params[:message][:body]
  )
end

推荐阅读