Language 1
<input type=“checkbox” name=“user_profile[language_ids][]” value=“2” /
Language 2
<input type=“checkbox” name=“user_profile[language_ids][]” value=“3” /
Language 3
<input type=“checkbox” name=“user_profile[language_ids][]” value=“4” /
Language 4
<input type=“checkbox” name=“user_profile[language_ids][]” value=“5” /
Language 5
I set session[:language_ids] = params[:user_profile][:language_ids]
When I retrieve that: @user_profile.language_ids = session[:language_ids]
and I save it, it works fine.
My problem is…I want to store those values in a database, but just
in 1 field.
So I created a string type field and save it. But the value looks
strange on the way out of the DB and I can’t set the @user_profile.language_ids to that value.
Is there a trick to saving this kind of a list of IDs to a DB field?
So I created a string type field and save it. But the value looks
strange on the way out of the DB and I can’t set the @user_profile.language_ids to that value.
Is there a trick to saving this kind of a list of IDs to a DB field?
You;ve got to convert it to a string. Either use serialize as Phillip
suggested or foo_ids = session[:language_ids].join(’,’) (and then the
corresponding split whenyou retrieve the row from the database). The
default to_s on Array doesn’t do anything very useful in this case.
So I created a string type field and save it. But the value looks
strange on the way out of the DB and I can’t set the @user_profile.language_ids to that value.
Is there a trick to saving this kind of a list of IDs to a DB field?
If you have an attribute that needs to be saved to the database as an
object, and retrieved as the same object, then specify the name of
that attribute using this method and it will be handled automatically.
The serialization is done through YAML. If class_name is specified,
the serialized object must be of that class on retrieval or
SerializationTypeMismatch will be raised.
Attributes
* attr_name - The field name that should be serialized.
* class_name - Optional, class name that the object type should
be equal to.
Example
Serialize a preferences attribute
class User
serialize :preferences
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.