Array to String Return to array conversion task

I am saving a bunch of id in a session like this.

session[:id_group] = 1,2,3,4,5

Because I need to save them to a database with a form.

In this form, I have a hidden field:

<%= form.text_field :group, :value => session[:id_group].inspect%>

I use validation to save the value in the database [1,2,3,4,5], not 12345

The problem is that when I get this value from the DB, I get [1,2,3,4,5] as a String. If I do this:

groups = game.group
=> [1,2,3,4,5]
group.class 
=>string

I can convert it to an array as follows:

groups = game.group.split(',')

but if i do


groups.each |group| do
  puts |group|.to_s
end

I get


[1
2
3
4
5]

And I need a clean id, so I can do something like


but then if I do
groups.each |id| do
  User.find_by_id(id)
end

How can I fix this mess? Thanks in advance.

+3
source share
2 answers

, . , , , .

- , :

<%= form.text_field :group, :value => session[:id_group].join(',') %>

, . - , , - .

, - :

@ids = params[:group].split(/,/)

@users = User.find_all_by_id(@ids)

, .

+2

:

groups.class
#=> String
groups = JSON.parse(groups)
#=> [1,2,3,4,5]
groups.class
#=> Array
0

Source: https://habr.com/ru/post/1732613/


All Articles