【问题标题】:rails polymorphic associations, redirection depending on model, using the model's controllerrails 多态关联,重定向取决于模型,使用模型的控制器
【发布时间】:2017-02-03 04:04:06
【问题描述】:

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

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,也不要给出不同的重定向,只定义前缀助手。

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

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

谢谢

【问题讨论】:

  • "有没有办法调用控制器模型中的方法。"怎么样:@notification.notifiable.is_a?(请求)
  • 您的术语有问题。单击某些内容不会“重定向到请求”,但我认为您可能过于拘泥于不在 Notifications_controller 中执行任何操作。您能否描述您希望看到的更具体的步骤?

标签: ruby-on-rails ruby redirect polymorphic-associations


【解决方案1】:

我最终为通知模型添加了一个属性 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

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

【讨论】:

  • 在这个项目中,添加在上下文中显示的通知和历史记录(每个上下文取决于用户所在的位置),因此他将查看特定的通知和历史记录。如果有人需要有关制作的详细信息,请随时询问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多