2

When saving our Video object we get a no method vide_url error when trying to redirect to the video#watch action and view the object

Admin/Video/Controller

def create
  @video = Video.create(user: User.first, title: params['title'], description: params['description'], file: params['video']['file'])
redirect_to @video
end

Video/Controller

def index
  @videos = Video.page(params[:page]||1)
end
def watch
  @video = Video.find_by!(id: params[:id])
end

Routes

get "video/index"
get "video/watch/:id" => 'video#watch'
namespace :admin do
  resources :video
  resources :playlist
end

Any idea what is going on? Is it because we are using custom routes for the videos?

4

2 回答 2

4

是的,这是您的自定义路线。redirect_to @video本质上调用url_for @video. 从文档中url_for

依赖命名路由

传递记录(如活动记录)而不是哈希作为选项参数将触发该记录的命名路由。查找将发生在类的名称上。所以传递一个 Workshop 对象将尝试使用 Workshop_path 路由。如果您有嵌套路由,例如 admin_workshop_path,则必须显式调用它(url_for 无法猜测该路由)。

所以,因为你有一个围绕该资源的命名空间,你需要这样做:

redirect_to admin_video_path(@video)

或者

redirect_to admin_video_url(@video)

更新

如果您想重定向到 watch 操作,您需要重定向到包含该操作的选项哈希:

redirect_to controller: :video, action: :watch, id: @video.id

或者在 routes.rb 中为您的监视路线命名:

get "video/watch/:id", to: 'video#watch', as: :watch_video

并重定向到该命名路线:

redirect_to watch_video_url(@video)
于 2013-09-10T14:31:35.100 回答
1

请尝试以下方法。

def create
  @video = Video.create(user: User.first, title: params['title'], description: params['description'], file: params['video']['file'])
  redirect_to admin_video_path(@video)
end
于 2013-09-10T14:25:46.320 回答