简体   繁体   中英

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. The problem I am having is assigning the selected state to a variable. Below is the 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.

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".

In your case params[:state][:abbr] will do the work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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