I'm pretty new to ember JS and having some issue returning a api_key object from the server on a post... I'm not sure if this is a problem with my rails serializer or a problem with the Ember itself! Any suggestions?
adapter
import DS from 'ember-data';
import Ember from 'ember';
export default DS.RESTAdapter.extend({
host: 'http://localhost:3000',
// =========================
// ERROR HANDLING
// =========================
ajaxError: function(jsXHR) {
var error = this._super(jsXHR);
if (jsXHR && jsXHR.status === 422) {
var response = Ember.$.parseJSON(jsXHR.responseText);
var errors = {};
if (response.errors) {
var jsonErrors = response.errors;
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
controllers/users/new.js
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Controller.extend({
actions: {
createUser: function() {
var router = this.get('target');
var _this = this;
var user = this.getProperties('name', 'email', 'username', 'password', 'password_confirmation');
user = this.store.createRecord('user', user);
user.save().then(function(apikey) {
==================
Get ember object back with apikey attached
==================
console.log(apikey)
// router.transitionTo('brands');
},
function(response) {
_this.set('errors', response);
});
}
}
});
routes/users/new.js
import Ember from 'ember';
export default Ember.Route.extend({
setupController: function(controller, model) {
this.controller.set('model', this.store.createRecord('user'));
}
});
rails end
class UsersController < ApplicationController
before_filter :ensure_authenticated_user, only: [:index]
def index
render json: User.all
end
def show
@user = User.find(params[:id])
if @user
render json: @user
else
render json: 'not found', status: 201
end
end
def create
user = User.create(user_params)
if user.new_record?
render json: { errors: user.errors.messages }, status: 422
else
render json: { api_key: user.session_api_key }, status: 201
end
end
private
def user_params
params.require(:user).permit(:name, :username, :email, :password, :password_confirmation)
end
end
class ApiKeySerializer < ActiveModel::Serializer
attributes :id, :access_token
has_one :user
end
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :username, :email
has_one :api_key
end
Aucun commentaire:
Enregistrer un commentaire