James
James

Reputation: 245

Rails not redirecting to object after save

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?

Upvotes: 2

Views: 1005

Answers (2)

Shadwell
Shadwell

Reputation: 34784

Yes, it is your custom routes. redirect_to @video essentially calls url_for @video. From the docs for url_for:

Relying on named routes

Passing a record (like an Active Record) instead of a hash as the options parameter will trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as admin_workshop_path you’ll have to call that explicitly (it’s impossible for url_for to guess that route).

So, because you've got a namespace around that resource you'll need to do:

redirect_to admin_video_path(@video)

or

redirect_to admin_video_url(@video)

Update

If you want to redirect to the watch action you'll need to either redirect to a hash of options including that action:

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

Or give your watch route a name in routes.rb:

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

And redirect to that named route:

redirect_to watch_video_url(@video)

Upvotes: 4

Bachan Smruty
Bachan Smruty

Reputation: 5734

Please, Try the followings.

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

Upvotes: 1

Related Questions