0

我想知道如何通过 JSON POST 在 rails 3 中保存对象?

问题是UsersController.rb无法识别JSON POST参数并假定请求中没有参数。

我有两个相同的创建方法,只是为了调试问题。提前致谢!

路由.rb

post 'users'          => "users#create"
match 'users/create'  => "users#create_user", :via => [ :post]

用户.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable,
         :validatable, :token_authenticatable #, :omniauthable

  has_many :leader_boards

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :authentication_token , :first_name, :large_profile_image_url, :last_name, :profile_image_url, :provider, :uid

  validates :email, :uniqueness => { :case_sensitive => false }
  validates :email, :first_name, :last_name, :presence => true
  validates :password, :password_confirmation, :presence => true
  validates :password, :length => { :minimum => 8 }

  def name
    return self.first_name.to_s + ' ' + self.last_name.to_s
  end
end

用户控制器.rb

module Api
  module V1
    class UsersController < ApplicationController
      before_filter :authenticate_user!, :except => [:create, :show, :update, :create_user, :facebook,:leader_board]
      respond_to :json

      def create
        @user = User.create(params[:user])
        begin
          @user.reset_authentication_token!
        rescue

        end
        respond_with @user
      end

      def create_user
        begin
          @user = User.new
          @user.email = params[:email]
          @user.password  = params[:password]
          @user.password_confirmation   = params[:password_confirmation]
          @user.first_name = params[:first_name]
          @user.last_name  = params[:last_name]
          @user.save
        rescue

        end
        respond_with @user
      end

JSON 发布

{ “email”:“jordanpass@jordanpass.cpm”,“first_name”:“mike”,“last_name”:“jordan”,“密码”:“jordanpass”,“password_confirmation”:“jordanpass”}

回复

{"errors":{"email":["can't be blank","can't be blank"],"password":["can't be blank","can't be blank","is too short (minimum is 8 characters)"],"first_name":["can't be blank"],"last_name":["can't be blank"],"password_confirmation":["can't be blank"]}}

示例帖子替代屏幕截图

4

1 回答 1

4

您的 JSON 帖子:

{ “email”:“jordanpass@jordanpass.cpm”,“first_name”:“mike”,“last_name”:“jordan”,“密码”:“jordanpass”,“password_confirmation”:“jordanpass”}

是不正确的。由于控制器正在寻找params[:user],您的 JSON 应该是:

{“用户”:{“电子邮件”:“jordanpass@jordanpass.cpm”,“first_name”:“mike”,“last_name”:“jordan”,“密码”:“jordanpass”,“password_confirmation”:“jordanpass”} }

于 2013-02-13T07:14:59.927 回答