且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ruby中覆盖[]括号?

更新时间:2023-02-18 15:23:10

您需要使用 params [:Jobs] [:clearance]



params 是所有请求参数的哈希值。但是 params [:Jobs ]也是全部的哈希:作业参数。所以调用 params [:Jobs] [:清除] 正在调用 [] > params [:Jobs] object passing :clearance in作为参数。


I am writing an Ajax request form with Ruby on Rails using a collection_select tag that looks like this:

<%= collection_select("Jobs", "clearance", @allClearances, "clearance", "clearance", {:prompt => "Select a Clearance"} )%>

Ruby then builds an HTML select tag with id = "Jobs_clearance" and name = "Jobs[clearance]"

I want to send the parameter to my controller, which looks like this:

class JobsController < ApplicationController
  def foo
    @clearance = params[:Jobs[clearance]]
  end

Unfortunately, Ruby only reads ":Jobs" as the symbol instead of ":Jobs[clearance]"
Is there a way to escape the []'s? backslash isn't working.

You need to use params[:Jobs][:clearance]

params is a hash of all the request parameters. But params[:Jobs] is ALSO a hash of all :Jobs parameters. So calling params[:Jobs][:clearance] is calling the [] method on the params[:Jobs] object passing :clearance in as a parameter.