Rails 多态关联,重定向取决于模型,使用模型的控制器



在我正在开发的应用程序中,我需要安装一个通知系统。

class Notification < ActiveRecord::Base
  belongs_to :notifiable, polymorphic: true
end
class Request < ActiveRecord::Base
 has_many :notifications, as: :notifiable
end
class Document < ActiveRecord::Base
 has_many :notifications, as: :notifiable
end

创建后,通知应该根据通知类型重定向到不同的视图,因此它可以用于相同的模型和不同的重定向(因此redirect_to通知。Notifiable不是一个解决方案,因为我需要许多不同的重定向相同的模型,而不仅仅是显示)。使用多态路径或url,也不给不同的重定向,只定义前缀帮助器。

我需要更明确的,例如这里让我们采取两种不同类型的通知,一个是提交请求,所以点击它将重定向到请求本身,但当请求完成时,用户将被重定向到他的仪表板。

我不想重定向到notifications_controller并在模型上测试,然后在通知类型上再次测试,我希望这里的多态性可以帮助。是否有一种方法可以调用控制器模型中的方法(模型是从多态关联中检测到的)

和感谢

我最终在通知模型中添加了一个属性message_type: integer。一旦通知被单击,重定向将始终是相同的:到NotificationController (redirect_notification)中的方法,现在通知已知,依赖模型也已知(来自多态关系)。在NotificationController中:

def redirect_notification    
   notification =Notification.find(params[:id]) // here i get the notification  
   notification.notifiable.get_notification_path(notification.message_type)
end

在使用notification.notifiable时,我们利用了多态。因此,我在每个与通知有多态关联的模型中定义了一个名为get_notification_path(message_type)的方法,例如:

class Document < ActiveRecord::Base
  has_many :notifications, as: :notifiable
  def get_notification_path(message_type)
    if message_type == 0
       "/documents"// this is just an example, here you can put any redirection you want, you can include url_helpers.
    elsif message_type == 1
       url_for user_path
    end
  end
end

这样,我得到我需要的重定向,使用多态关联,而不添加不必要的路由。

最新更新