devans725
devans725

Reputation: 9

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.

Upvotes: 0

Views: 84

Answers (1)

Tushar Kulkarni
Tushar Kulkarni

Reputation: 134

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.

Upvotes: 3

Related Questions