How do I get the value of a hash in Rails?

Asked

Viewed 747 times

2

I have some checkboxs inside a form in the view, which values are being sent to the controller by params to the index.

obs. I’m sending the checkbox values from the view index to itself, I need the checkbox values in a variable.

in the controller I’m getting the params like this:

 @post = params[:checkbox_array]

in the view, is the same:

post: <% @post %>

after the page refreshes, the variable with the second value appears:

post: {"2m"=>"1", "2"=>"2", "3m"=>"3"}

I just want to take all the "Keys" or all the "values" and assign it to another variable

From what I know it should be something like this in the controller:

@variavel1 = @post.key or @variavel2 = @post.values

@post.select, @post.sample... also does not work, when accessing the page I get "Undefined method"

What should I do to filter this hash I’m getting and have an output like:

["2m", "2", "3m"] or ["1", "2", "3"] ?

1 answer

1

You’re right, the method you seek is keys or values, example:

{"2m"=>"1", "2"=>"2", "3m"=>"3"}.keys
=> ["2m", "2", "3m"]

{"2m"=>"1", "2"=>"2", "3m"=>"3"}.values
=> ["1", "2", "3"]

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.