Felix
Felix

Reputation: 5619

rails ActionView::MissingTemplate ajax function

I call a Rails controller function with an ajax request. It works But I got an error back:

ActionView::MissingTemplate

Controller funktion is:

# Aktiviert einen Kurs. Diese Action wird von einem AJAX-Aufruf aus    aufgerufen
 def activate
    @course = Course.find params[:id]
    return false unless check_authorization @course
   @course.active = params[:active]
   @course.save

   redirect_to :back
end

ajax call looks like this:

$.ajax({
       url: '<%= url_for(:controller => "courses", :action => "activate_lesson") %>',
       data: {"id": <%= lesson.id%>, "active": 0}
                })
                        .done(function () {
                            saved();
                        })
                        .fail(function () {
                            notsaved();
                        })

How can I resolve the error?

Upvotes: 0

Views: 664

Answers (2)

Nermin
Nermin

Reputation: 6100

When you use action inside controller, if you do not say what specific template it should render it searches for

app/views/controller_name_without_word_controller/action_name.html.*

In your case it is searching for app/views/controller_name/activate.html.* to render it, but you do not have that file.

Solution is to return json response, because you are using ajax, but you can return html

You can write:

 def activate
   @course = Course.find params[:id]
   return false unless check_authorization @course
   @course.active = params[:active]
   @course.save
   render json: @course # or whatever you want to return
end

Upvotes: 2

RAJ
RAJ

Reputation: 9747

You need to render json from your controller.

before_filter :authorized?, :only => :activate

def activate
  @course.active = params[:active]
  if @course.save
    render :json => {:status => :ok}
  else
    render :json => {:errors => @course.errors}
  end
end

def authorized?
  @course = Course.find params[:id]
  render :json => {:status => 401, :error => :unauthorized} unless check_authorization(@course)
end

Upvotes: 1

Related Questions