samedi 10 juin 2017

Passing data from an ember route to a rails controller

I am trying to post an account resource from my front end (an ember.js application) to my back end (a rails application). Whenever I try and run my code as I have it currently written, it bounces off, throwing me a 422 unprocessable entity error.

app/routes/create-accounts.js (params is an object containing a username, a creator boolean variable and a contentType string):

import Ember from 'ember';
export default Ember.Route.extend({
    createAccount (params) {
      let account = this.get('store').createRecord('account', params);
      account.save();
    }
});

app/models/account.js

import DS from 'ember-data';
export default DS.Model.extend({
  user_name: DS.attr('string'),
  content_type: DS.attr('string'),
  creator: DS.attr('boolean'),
  coinbase_email: DS.attr('string'),
  user_id: DS.belongsTo('user')
});

app/controllers/accounts_controller.rb

def create
    if current_user.account
      raise 'Already has an account'
    else
      @account = Account.new(account_params)
      @account.user = current_user
      @account.coinbase_email = current_user.email
      if @account.save
        render json: @account, status: :created
      else
        render json: @account.errors, status: :unprocessable_entity
      end
    end
  end

db/schema.rb

create_table "accounts", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "user_name"
    t.float    "balance"
    t.boolean  "creator"
    t.string   "content_type"
    t.string   "content_list"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.string   "coinbase_email"
    t.index ["user_id"], name: "index_accounts_on_user_id", using: :btree
  end

The error I'm getting is telling me that all the parameters of the account object being passed to my database are nil. How would I go about passing an object with valid parameters to my controller?




Aucun commentaire:

Enregistrer un commentaire