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

rails polymorphic associations, redirection depending on model, using the model's controller

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

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 notification.notifiable 不是解决方案,因为对于同一个模型,我需要许多不同的重定向,而不仅仅是节目)。 使用 polymorphic_path 或 url,也不要提供不同的重定向,只定义前缀助手。

我更明确地需要什么,例如让我们采用两种不同类型的通知,一种是提交请求的通知,因此单击它会重定向到请求本身,但是当请求完成时,用户将被重定向到他的仪表板。

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

谢谢

我最终向通知模型添加了一个属性,message_type:整数。 单击通知后,重定向将始终相同:到 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

这样,我得到了我需要的重定向,使用多态关联并且没有添加不需要的路由。