标签: rails-api

在JSON输出中隐藏password_digest错误消息

我正在使用rails-api gem构建一个简单的JSON API.

车型/ user.rb:

class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :email, :password, :password_confirmation

  validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i }
  validates :password, presence: { on: :create }, length: { minimum: 6 }
end
Run Code Online (Sandbox Code Playgroud)

当我尝试在没有密码的情况下注册时,这是我获得的JSON输出:

{
  "errors": {
      "password_digest": [
          "can't be blank"
      ],
      "password": [
          "can't be blank",
          "is too short (minimum is 6 characters)"
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

是否可以隐藏password_digest的错误消息?我正在控制器中使用respond_with返回@user对象.

我尝试了以下但没有运气(它只是重复错误"不能为空"):

validates :password_digest, presence: false
Run Code Online (Sandbox Code Playgroud)

validation json ruby-on-rails rails-api

1
推荐指数
1
解决办法
875
查看次数

Factory Girl使用rails-api未初始化常量型号名称

我正在尝试为我的用户模型创建一个工厂,但是当我运行rspec时,我得到了

Failure/Error: user = build(:user, email: "invalid@email.com")
 NameError:
   uninitialized constant User
Run Code Online (Sandbox Code Playgroud)

当我跳进rails控制台时,我可以做User.all,它会返回我拥有的用户并且FactoryGirl.build(:user, email: "invalid@email.com")工作正常,所以我不确定问题出在哪里.

我用rails-api创建了项目,使用rails 4.2 ruby​​ 2.2

# spec/spec_helper.rb
# i have to set spec/factories as the location explicitly or it won't find the factories

  require 'factory_girl_rails'
  RSpec.configure do |config|
    config.include FactoryGirl::Syntax::Methods

    FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)]
    FactoryGirl.find_definitions
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
    end

    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = true
    end

    config.filter_run :focus
    config.run_all_when_everything_filtered = true

    if config.files_to_run.one?
      config.default_formatter = 'doc'
    end

    config.profile_examples = 10
    config.order = …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails rails-api factory-bot

1
推荐指数
1
解决办法
1508
查看次数

为什么我得到未定义的方法`cookies'?

我正在尝试使用single_access_token为我的rails后端应用程序设置Authlogic(我正在使用rails-api gem).

我正在关注这个例子:http://blog.centresource.com/2013/06/04/using-ember-auth-with-rails-3-and-authlogic/

到目前为止,我能够创建用户,但是当我尝试登录时,它在user_session.save失败:

NoMethodError in Api::V1::UserSessionsController#create
undefined method `cookies' for #<Api::V1::UserSessionsController:0x00000004528cb8>
Run Code Online (Sandbox Code Playgroud)

根据我在这里找到的类似问题,我必须将Authlogic配置为:

  acts_as_authentic do |c|
    c.login_field = :email
    c.maintain_sessions = false
  end
Run Code Online (Sandbox Code Playgroud)

在我的用户模型上.然而,它一直在失败.我假设当UserSession被保存时,Authlogic尝试更新User上的魔术字段,但我不知道为什么还在尝试使用cookie.

ruby cookies ruby-on-rails authlogic rails-api

1
推荐指数
2
解决办法
3598
查看次数

根据Rspec的说法,为什么机架式磁盘不能过滤传入的请求

我想我的Rails 5 API专用应用程序,现在正在运行http://localhost:3000,只接受来自我的NodeJS前端应用程序的请求,现在正在运行http://localhost:8888.

所以我配置/config/initializers/cors.rb如下:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "http://localhost:8888"
    resource "*",
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
Run Code Online (Sandbox Code Playgroud)

我写了这个测试:

#/spec/request/cors_request_spec.rb

RSpec.feature "CORS protection", type: :request do
  it "should accept a request from a whitelisted domain" do
    get "/api/v1/bodies.json", nil, "HTTP_ORIGIN": "http://localhost:8888"
    expect(response.status).to eql(200)
  end
  it "should reject a request from a non-whitelisted domain" do
    get "/api/v1/bodies.json", nil, "HTTP_ORIGIN": "https://foreign.domain"
    expect(response.status).to eql(406)
  end
end
Run Code Online (Sandbox Code Playgroud)

第一个测试按预期传递.但第二个是失败,响应代码为200.为什么?

(顺便说一句,我没有使用406响应代码;只是表示请求不会被执行的代码.)

rspec ruby-on-rails cors rails-api rack-cors

1
推荐指数
1
解决办法
949
查看次数

Rails 关注点,如何在 api 控制器中包含关注点

我正在构建一个 Rails api,目前具有以下文件夹结构:

在此处输入图片说明

error_serializer.rb 文件是一个模块:

module ErrorSerializer
  extend ActiveSupport::Concern

  ...methods here...
end
Run Code Online (Sandbox Code Playgroud)

我可以将其包含在任何 api 控制器中,例如:

class Api::TemplatesController < ApiController
  include ErrorSerializer
  ...
end
Run Code Online (Sandbox Code Playgroud)

但是由于这个 errors_serializer 模块只与 api 控制器相关,我想将文件移动到 ' api/concerns/error_serializer.rb'。

但这会产生错误:

ActionController::RoutingError (uninitialized constant Api::TemplatesController::ErrorSerializer)
Run Code Online (Sandbox Code Playgroud)

我尝试将文件内的名称更改为:

module Api::ErrorSerialzer
Run Code Online (Sandbox Code Playgroud)

但得到了同样的错误。

那么我必须更改什么才能移动该文件?

ruby-on-rails rails-api activesupport-concern

1
推荐指数
1
解决办法
4049
查看次数

rails api 和 react api 的分页

我正在构建一个网络应用程序。为此,我将rails其用作backend. 也react用于frontend. 我有一个模型user。我想向users网站用户显示所有内容及其详细信息。所以我有大约 10,000 多个用户。所以我不能一次性将所有用户发送到前端。我想一次只显示 50 个用户。因此,要查看接下来的 50 个用户,前端会向我发送一个新请求以获取接下来的 50 个用户,依此类推。所以我没有得到正确的路径如何构建它。

现在我把所有的用户都这样了,我的服务器也挂了。

我的 users_controller.rb

 class UsersController < ApplicationController
    def index
      users = User.all
      render_success(:ok, users, meta: { message: 'User sucessfully send' })
    end
 end
Run Code Online (Sandbox Code Playgroud)

简而言之 - 我只想在每个请求中向前端发送有限数量的数据。

pagination ruby-on-rails rails-api reactjs

1
推荐指数
2
解决办法
3281
查看次数

更新具有相同图像的模型时 ActiveSupport::MessageVerifier::InvalidSignature 错误

在不更改图像的情况下更新包含附加图像的模型时,我无法弄清楚出现错误的原因:

Processing by PostsController#update as JSONAPI
  Parameters: {"data"=>{"id"=>"28", "attributes"=>{"title"=>"post-1", "body"=>"azertyui", "archived"=>true, "tag_ids"=>[11, 12, 13], "photo"=>"http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBFZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--86e7464f36c2eddf776573af7b9e61d969287158/diagram.png"}, "type"=>"posts"}, "id"=>"28"}
Run Code Online (Sandbox Code Playgroud)

我得到的错误如下:

Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.5ms)
ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):
app/controllers/posts_controller.rb:30:in `update'
Run Code Online (Sandbox Code Playgroud)

这是控制器更新操作代码:

def update
    if @post.update(post_params)
      render json: @post
    else
      respond_with_errors @post
    end
  end
Run Code Online (Sandbox Code Playgroud)

这是PostSerializer看起来的样子:

class PostSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attributes :id, :title, :body, :tag_ids, :archived, :photo

  def photo
    rails_blob_url(object.photo) if object.photo.attached?
  end
end
Run Code Online (Sandbox Code Playgroud)

我正在使用 Rails 5.2.0 API。我错过了什么?

ruby-on-rails rails-api

1
推荐指数
1
解决办法
3528
查看次数

设计登录 rails 4 的自定义参数

我正在使用 Rails 4 构建 API,并使用Devise进行身份验证。我也覆盖了SessionsController登录用户。我有一个资源被调用user并设置了适当的devise_for路由。该create操作如下:

def create
 self.resource = warden.authenticate(auth_options)
 ## Handle error / success json based on resource
 .......
end
Run Code Online (Sandbox Code Playgroud)

由于资源是user如果我curl对数据参数进行处理,例如:

{"user": {"email": "hello@example.org", "password": "password"} }
Run Code Online (Sandbox Code Playgroud)

有用。

我只想知道如何自定义参数,以便devise/warden能够适当地选择它。即,我想发送以下请求数据,它应该进行身份验证:

{"email": "hello@example.org", "password": "password"}
Run Code Online (Sandbox Code Playgroud)

devise warden rails-api ruby-on-rails-4

0
推荐指数
1
解决办法
1580
查看次数