Rails如何返回单个JSON对象而不是JSON对象数组?

时间:2015-05-19 09:34:52

标签: ruby-on-rails json

我限制为1,所以我认为在这种情况下返回一个对象与.find_by_email

相同

代码:

  # GET /users/:identified/type/:social_type
  # Returns a single record - so limit 1
  def find
    @user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).limit(1)

    if not @user.empty?
      render json: @user.as_json, status: :created
    else
      render json: @user, status: :not_found
    end
  end

当前回应:

[{"id":7,"voy_num":null,"voy_pin":null}]

如何确保我返回一个JSON object

1 个答案:

答案 0 :(得分:1)

要获取单个对象,请将firstwhere一起使用,如下所示:

@user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).first