从 Rails 上的 Ruby 中的 ActionController::Parameters 中获取密钥

Grabbing the key from the ActionController::Parameters in Ruby on Rails

这是我的代码

  def create
    @p_site = PSite.find(params.require(:plan_for).first[0])
    authorize @p_site, :c_s?
    if @p_site.save
      redirect_to :root, notice: "successfully added"
    else
      render :new
    end
  end

当我 运行 时,我得到 undefined method 'first' for <ActionController::Parameters:0x00005623c4d56f68>

我的参数[:plan_for] 看起来像这样: #<ActionController::Parameters {"82"=>"annual"} permitted: false>

我需要获取82的值并在PSite中查找。我该怎么做?

Params 在这里是一个 Hash 而不是数组。哈希的结构方式是键值对。 例如:

my_hash = { key: "Some Value" }
mz_hash[:key] #=> "Some Value"

所以我想知道的第一件事是为什么你在这里使用 82 作为密钥?如果它是一个 id,我会将其重组为如下所示:{ id: 82, recurrence: "annual" }

专门针对您的案例:

params[:plan_for]["82"]          #=> "annual"
params.require(:plan_for)["82"]  #=> "annual"

# OR very dirty
params[:plan_for].values.first   #=> "annual"
params[:plan_for].keys.first     #=> "82"

你可能会看到上面的前两行是如何工作的,除非“82”是你所有参数的键(在这种情况下命名它更好!)而后者现在可能是你代码的一个肮脏的解决方案但是我也不推荐。

查看 ruby hashes

的文档

我首先允许我的参数,然后将其转换为散列并使用 first[0] 访问它。

@pp = params.require(:plan_for).允许!.to_h

@p_site = PractitionerSite.find(@pp.first[0])

这将抢走我的价值 82