【问题标题】:Rails 4 Api returning all user dataRails 4 Api 返回所有用户数据
【发布时间】:2014-04-29 06:26:18
【问题描述】:

我有一个正在为手机构建的 api,当我发出 get 请求时,我试图只为当前用户返回数据:

API 控制器:

**Shows me one specific user -- which is what I want**
respond_with Mibox.where(:user_id  => 19 ).load

**Shows me all user boxes**
respond_with Mibox.all
respond_with Mibox.where(:user_id  => session[:user_id]).load
respond_with Mibox.where(:user_id  => session[:current_user] ).load

如何将范围限制为当前用户或当前会话用户 ID?由于某种原因,它说它找不到 current_user,即使 Devise 应该使它可用于所有控制器和视图。我正在使用带有内置 api for rails 的设计。我正在使用旧的授权令牌方法(一旦完成,我将更新)。

respond_with Mibox.where(user: current_user).load

Started GET "/api/v1/miboxes.json" for 127.0.0.1 at 2014-03-21 13:23:08 -0500
Processing by Api::V1::MiboxesController#index as JSON
  Parameters: {"mibox"=>{}}
  User Exists (0.1ms)  SELECT 1 AS one FROM "users" WHERE "users"."authentication_token" = 'vNpqxmNcy8oP1V8BYzmF' LIMIT 1
  Mibox Load (0.2ms)  SELECT "miboxes".* FROM "miboxes" WHERE "miboxes"."user" IS NULL
SQLite3::SQLException: no such column: miboxes.user: SELECT "miboxes".* FROM "miboxes"  WHERE "miboxes"."user" IS NULL
Completed 500 Internal Server Error in 7ms

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: miboxes.user: SELECT "miboxes".* FROM "miboxes"  WHERE "miboxes"."user" IS NULL):
  app/controllers/api/v1/miboxes_controller.rb:52:in `index'

respond_with Mibox.where(user_id: current_user.id).load

`Started GET "/api/v1/miboxes.json" for 127.0.0.1 at 2014-03-21 13:19:44 -0500
Processing by Api::V1::MiboxesController#index as JSON
  Parameters: {"mibox"=>{}}
  User Exists (0.1ms)  SELECT 1 AS one FROM "users" WHERE "users"."authentication_token" = 'vNpqxmNcy8oP1V8BYzmF' LIMIT 1
Completed 500 Internal Server Error in 6ms

NoMethodError (undefined method `id' for nil:NilClass):
  app/controllers/api/v1/miboxes_controller.rb:52:in `index'`

这是 mibox 架构:

create_table "miboxes", force: true do |t|
    t.text     "content"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "myboximages"
    t.text     "name"
    t.string   "qrcode"
    t.text     "location"
  end

  add_index "miboxes", ["user_id", "created_at"], name: "index_miboxes_on_user_id_and_created_at"

控制器

   class Api::V1::MiboxesController < ApplicationController
  before_filter :restrict_access
  skip_before_filter :verify_authenticity_token,
                     :if => Proc.new { |c| c.request.format == 'application/json' }
  after_filter :cors_access

  respond_to :json

  def cors_access
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    headers['Access-Control-Max-Age'] = "1728000"
  end


  rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception|
    error = {}
    error[parameter_missing_exception.param] = ['parameter is required']
    response = { errors: [error] }
    respond_to do |format|
      format.json { render json: response, status: :unprocessable_entity }
    end
  end




  def index
    respond_with Mibox.where(user_id: current_user).load
  end






  def show
    respond_with Mibox.find(params[:id])
    #@mibox = current_user.miboxes.find(params[:id])
  end

  def create
    respond_with Mibox.create(mibox_params)
  end

  def update
    respond_with Mibox.update(params[:id], mibox_params)
  end

  def destroy
    respond_with Mibox.destroy(params[:id])
  end

  private
  def set_mibox
    @mibox = Mibox.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def mibox_params
    #params.require(:mibox).permit!
    params.require(:mibox).permit(:content, :location, :myboximages, :myboximages_cache, :remove_myboximages, :name, :user_id, tag_list: [])
  end


  def restrict_access
    authenticate_or_request_with_http_token do |token, options|
      User.exists?(authentication_token: token)
      #User.find_by(params[:user_id])
    end
  end
end

【问题讨论】:

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


    【解决方案1】:

    参考Devise documentation,可以看到正确的helper方法是#current_user

    即:

    respond_with Mibox.where(user: current_user).load
    

    respond_with Mibox.where(user_id: current_user.id).load
    

    当然,这假设您已经对用户进行了身份验证。

    【讨论】:

    • 感谢您的建议。我已经用输出更新了问题。不幸的是,我得到了错误。我已经发布了架构,看看是否有帮助。
    • 问题很容易发现:current_user 为空。你确定你已经授权了用户?即:关注devise controller structure?
    • 啊。当我添加 before_filter :authenticate_user! 时,它要求我登录。我登录并获取身份验证令牌并执行获取,然后它拒绝我:“错误”:“您需要先登录或注册才能继续。”我正在使用一个脱离 auth_tokens 的旧教程此时您会推荐什么?我在上面添加了我的控制器。
    • 如果您在浏览器之外使用 API,您可能没有存储会话。实际上,我最近写了一篇关于 API authentication with Devise 的博文,你可能想看看。
    • 这有点像我想的。似乎没有可以依赖的会话 ID。我会仔细阅读您的帖子并再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    相关资源
    最近更新 更多