【问题标题】:Creating User with Rails API and JSON?使用 Rails API 和 JSON 创建用户?
【发布时间】:2013-12-02 04:33:15
【问题描述】:

所以我在 Rails 中测试了一个非常简单的 API,看看我是否可以使用 Chrome 插件 Postman(REST 客户端扩展)在本地创建用户。

在我的 rails 应用程序中,我为我的 API 设置了一个文件夹/命名空间,每当我尝试创建我的用户时,都会收到以下错误: 缺少模板 api/v1/users/create, application/create with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}。搜索:*“PATH/app/views”

我正在使用 Rails 4.0.1 和 Ruby 2.0

我在下面发布我发布的内容的屏幕截图:

module Api
     module V1
    class UsersController < ApplicationController
        class User < ::User
            # add any hacks
        end

        respond_to :json

        def index
            respond_with User.all
        end

        def show
            respond_with User.find(params[:id])
        end

        def new
            @user = User.new
        end

        def create
            @user = User.create(user_params)
            # respond_with(@user)

            if @user.save
                # render json: @user, status: :created, location: @user
                redirect_to @user
            end
        end

        private

            def user_params
              params.require(:user).permit(:name, :age, :location) if params[:user]
            end
    end
  end
end

所以根据我的 user_params,我应该能够创建一个新用户,对吗? 如果您需要任何其他信息,请告诉我,我会尽快回复! 谢谢!

【问题讨论】:

    标签: ruby-on-rails json api ruby-on-rails-4


    【解决方案1】:

    您可以使用 API 创建用户。

    1) 首先,您需要在您的 routes.rb 中放置适当的资源:

    YourApp::Application.routes.draw do
      namespace :api do
        namespace :v1 do
         resources :users
        end
        namespace :v2 do
        # ... if needed
        end
      end
    
      root to: 'users#index'
    end
    

    2) 您需要创建一个 RESTfull 样式的控制器来处理请求。这里是如何实现您的“创建”操作的。

    def create
      respond_with User.create(fio: params[:fio], phone: params[:phone], region: params[:region], updated_at: Time.now)
    end
    

    使用 respond_to 的“创建”示例:

    def create
        # ...
        respond_to do |format|
          format.html {render text: "Your data was sucessfully loaded. Thanks"}
          format.json { 
                       User.create(... params ...)
                       render text: User.last.to_json  # !
                      }
        end
      end
    

    如果您需要特别的回复,请参阅有关 respond_withrespond_to 的文档。

    也可以是有关 API 构建的有用 railscasts 剧集:#350#352

    附:文件夹/命名空间/v1/users_controller 应与模块 Api 中的类名相同

    P.S.2 你可以观察我的应用程序,在那里你可能会发现一些有用的东西(与你的应用程序相同 - 用于记录创建的简单 API)-myApp

    users_controller 示例(controllers/api/v1/users_controller.rb):

    #encoding: utf-8
    
        module Api
          module V1
            class UsersController < ApplicationController # Api::BaseController
              before_filter :authenticate_user!, except: [:create, :index]
    
              respond_to :json
    
              def index
            #respond_with
    
                respond_to do |format|
                  format.html {render text: "Your data was sucessfully loaded. Thanks"}
                  format.json { render text: User.last.to_json }
                end
              end
    
              def show
                respond_with User.find(params[:id])
              end
    
              def create
                respond_with User.create(access_token: params[:access_token], city: params[:city], created_at: Time.now, phone: params[:phone], region: params[:region], updated_at: Time.now)
              end
    
              def update
                respond_with User.update(params[:id], params[:users])
              end
    
              def destroy
                respond_with User.destroy(params[:id])
              end
            end
          end
        end
    

    【讨论】:

    • 非常感谢!这很有帮助。我有一些余地,但仍然有点卡住......你的意思是我应该有两个 users_controller 吗?一个在主应用程序中,一个在我的 API 文件夹中?因为现在我有 2 个并且无法区分应该去哪里。
    • 是的,您可以根据需要拥有尽可能多的 users_controllers,因为它们位于不同的命名空间中(一个是您的主要 users_controller,其他在 controllers/api/v1/users_controller.rb、controllers/api/ v2/users_controller.rb, ...等)。
    • 我只是说你有一个 respond_to 和一个 respond_with 例子,我不确定你是否打算把一个放在 API 版本中,一个放在另一个......
    • 好吧,我希望现在很清楚。如果您有任何问题,请告诉我。
    • 其实,我有一个相关的问题:现在我有一个 user_params 的私有定义,除了我需要提交的数组之外,它似乎正在工作。在表单中,我通常使用复选框,但在这种情况下,我试图将流派分配给用户。 (:genre_ids => []) 我如何通过 JSON 提交这个(或作为 URL 参数?)
    【解决方案2】:

    redirect 不返回,所以你的create 方法会一直寻找要渲染的模板,然后发现没有匹配的模板。

    要修复,您需要显式返回redirect

     if @user.save
       return redirect_to(@user)
     end
    

    你还需要注意@user的默认url。在这种情况下,最好明确分配一个命名路径,比如redirect_to(user_path(@user))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多