Billy Logan
Billy Logan

Reputation: 2520

How to make Angular and Rails interact? Unknown format error

I have ngResource directive included in my first project in order to be able to interact with RESTful API.

Then I setup my factory like this:

angular.module('app').factory('User', [
  '$resource', function($resource) {
    return $resource('/api/user_login/:id', { id: '@id' }, {
      update: { method: 'PUT' }
    });
  }
]);

In my controller I try to save User i.e to send POST request.

app.controller('loginCtrl', [
  '$scope', 'User', function($scope, User) {
    return User.save();
  }
]);

My second project's controller look like the following. I'm trying to reference create action.

class UserSessionsController < UserApplicationController
  respond_to :js, only: :create

  def create
    if @counterparty
      session[:counterparty_id] = @counterparty.id
      @counterparty.update(signed_in: true)
    else
      flash.now[:error] = 'Invalid email or password'
    end

    respond_with(@counterparty, layout: false)
  end
end

As a result I'm getting ActionController::UnknownFormat.

enter image description here

Started POST "/user_login" for 127.0.0.1 at 2016-02-18 16:04:58 +0200
Started POST "/user_login" for 127.0.0.1 at 2016-02-18 16:04:58 +0200
Processing by UserSessionsController#create as HTML
Processing by UserSessionsController#create as HTML
  Counterparty Load (0.3ms)  SELECT  `counterparties`.* FROM `counterparties`  WHERE `counterparties`.`email` IS NULL AND `counterparties`.`password` IS NULL LIMIT 1
  Counterparty Load (0.3ms)  SELECT  `counterparties`.* FROM `counterparties`  WHERE `counterparties`.`email` IS NULL AND `counterparties`.`password` IS NULL LIMIT 1
Completed 406 Not Acceptable in 1ms
Completed 406 Not Acceptable in 1ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/user_sessions_controller.rb:13:in `create'

How can I solve this?

Upvotes: 1

Views: 179

Answers (2)

Pitabas Prathal
Pitabas Prathal

Reputation: 1012

Replace the create function with following function

    def create
      respond_to do |format|
       if @counterparty
         session[:counterparty_id] = @counterparty.id
         @counterparty.update(signed_in: true)
         format.json  { render :json => @counterparty.to_json ,status: :ok}
       else
         format.json  { render :json => 'Invalid email or password',status: :unprocessable_entity}
       end
      end
   end

Upvotes: 1

mr_sudaca
mr_sudaca

Reputation: 1176

Change respond_to :js, only: :create to respond_to :json, only: :create

user factory is doing a request in json format, although the controller should respond to js (json included) that didn't work for op, so it's necessary to set respond_to json explicitly

Upvotes: 2

Related Questions