简体   繁体   English

Ruby on Rails从嵌套参数分配变量

[英]Ruby on Rails assign variable from nested params

I am trying to create a simple paycheck calculator. 我正在尝试创建一个简单的薪水计算器。 I have assigned most of the variables for calculation like this: @hours = params[:hours].to_i I created a model for the states and created a dropdown box with: <%= collection_select(:state, :abbr, State.all, :abbr, :abbr) %> This seems to work as I want. 我已经为计算分配了大多数变量,如下所示: @hours = params[:hours].to_i我为各州创建了一个模型,并创建了一个下拉框,其中包括: <%= collection_select(:state, :abbr, State.all, :abbr, :abbr) %>这似乎可以按照我的要求工作。 The problem I am having is assigning the selected state to a variable. 我遇到的问题是将所选状态分配给变量。 Below is the debug(params): 下面是debug(params):

--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  utf8: "✓"
  hours: '80'
  rate: '15'
  allowances: '1'
  marital_status: S
  pay_period: '1'
  state: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
    abbr: AL
  commit: Submit
  controller: calc_page
  action: home
permitted: false

I don't know if this is an error in syntax or I am completely missing something. 我不知道这是语法错误还是我完全丢失了某些内容。 I have tried: @state = params[:state["abbr"]] @state = params[:state]["abbr"] among many others. 我尝试过: @state = params[:state["abbr"]] @state = params[:state]["abbr"]等。

Any advice or guidance is appreciated or if i need to provide more information. 任何建议或指导表示赞赏,或者如果我需要提供更多信息。

Thanks. 谢谢。

When you need to access any nested params, for example 例如,当您需要访问任何嵌套参数时

a:
 b:
  c: "hello"

then params[:a][:b][:c] will give you output "hello". 然后params [:a] [:b] [:c]将为您输出“ hello”。

In your case params[:state][:abbr] will do the work. 在您的情况下, params [:state] [:abbr]将完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM