I'm saving a bunch of ID's to the session like this.
session[:id_group] = 1,2,3,4,5
Because I need to save them to a data base with a form.
In that form I have hidden-field :
<%= form.text_field :group, :value => session[:id_group].inspect%>
I use the inspect so that the value saved to the database gets to be [1,2,3,4,5] and not 12345
The problem is, when I get that value from the DB I get [1,2,3,4,5] as a String. If I do:
groups = game.group
=> [1,2,3,4,5]
group.class
=>string
I can convert it to an array like this:
groups = game.group.split(',')
but then if I do
groups.each |group| do
puts |group|.to_s
end
I get
[1
2
3
4
5]
And I need the clean ID's 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开发者_JS百科 in advance.
You shouldn't be encoding your values using inspect. That will get re-encoded into a literal string, which is probably not your intention.
The correct way to put things in your form is to do the opposite of how you want to decode them:
<%= form.text_field :group, :value => session[:id_group].join(',') %>
Where join and split are matched up properly, it will work. The counterpart to inspect is eval and you really do not want to do that as someone can run arbitrary code that way.
As a note, you can also load a bunch of users with a single query using something like:
@ids = params[:group].split(/,/)
@users = User.find_all_by_id(@ids)
This is much more efficient than loading them in one at a time.
See: Convert a stringified array back to array
groups.class
#=> String
groups = JSON.parse(groups)
#=> [1,2,3,4,5]
groups.class
#=> Array
精彩评论