admin命名空间中的redirect_to对象

时间:2012-06-02 19:02:03

标签: ruby-on-rails ruby-on-rails-3 redirect routes

在Rails中,如果您已将对象声明为路径中的资源,则可以将对象传递给redirect_to

redirect_to @post

我有一个属于所有者的多态对象Attachment@attachment.owner可以是任何对象。我需要重定向到附件的所有者,但附件及其所有者都是管理命名空间中的资源:

namespace :admin do
  resources :attachments, :posts, :comments #etc
end

如果我知道@attachment.owner是一个帖子,我可以redirect_to admin_post_path(@attachment.owner),但由于它可能是任何对象,我该如何进行重定向?

2 个答案:

答案 0 :(得分:9)

您可以使用polymorphic_path

polymorphic_path([:admin, @attachment.owner])

答案 1 :(得分:0)

redirect_to将带符号作为参数。定义具有相同名称的私有方法,并评估该方法中的url。

redirect_to :my_owner

private

define my_owner
  <evaluate the path here>
end