Ruby 向哈希中添加字段

Ruby 向哈希中添加字段,ruby,Ruby,我得到下面代码的以下错误 undefined method `push=' for {"organisation_id"=>1}:Hash 如果在URL中传递了角色的参数,我想将其添加为查询参数。我来自PHP开发背景,因此我发现管理Rails对象/数组很困难 def index case @the_current_user.role when 'admin' query_params = {"organisation_id"=> @the_cur

我得到下面代码的以下错误

undefined method `push=' for {"organisation_id"=>1}:Hash
如果在URL中传递了角色的参数,我想将其添加为查询参数。我来自PHP开发背景,因此我发现管理Rails对象/数组很困难

def index
    case @the_current_user.role
      when 'admin'
        query_params = {"organisation_id"=> @the_current_user.organisation_id}
      else
        query_params = {"organisation_id" => @the_current_user.organisation_id, "team_id" => @the_current_user.team_id}
    end

    if params[:role]
      query_params.push = {"role" => params[:role]}
    end

    @users = User.all(query_params).offset(@offset.to_i).limit(@limit.to_i)
    render json: @users
  end

在Ruby中,如果要合并两个哈希,请使用Hashmerge方法。试试这个:

query_params.merge!({"role" => params[:role]})

我认为您没有注意到查询参数是散列而不是数组。不能将值推送到散列。可以在散列中设置键的值。 所以你可以这样做

query_params["role"] = params[:role]

这非常有效,谢谢。如果我的回答对您有帮助,请将其标记为已接受。快乐编码: