Converting Array to String in a model using before filters

Hi,

I have a list coming in a field like :selected_lists => [1,2,3,4]

from a form
while storing it in a database i need to join this list into a
string

so then in my model class,


  1. Added a filter before_save :convert_array_to_string
  2. Added an attr_accessor :selected_lists

def convert_array_to_string
self.lists_selected = self.lists_selected.join(",")
puts self.lists_selected
return true
end

so that before saving i call a function to format the array to
string and store it using attr_accessor method
I printed the “self.lists_selected” and i got “1,2,3,4” as the
result

I thought this would do my job
I am wondering why ‘nil’ is stored in the table.
Please help me out off this guys.

Regards,
Vimal Das

I have a list coming in a field like :selected_lists => [1,2,3,4]

from a form
Correction :selected_lists => [1,2,3,4] to ---------> :lists_selected
=> [1,2,3,4]
Regards,
Vimal Das

So, is there anyother way to carry this out of the box

Regards,
Vimal Das

On 19 Mar 2009, at 13:16, vimal wrote:


so that before saving i call a function to format the array to
string and store it using attr_accessor method
I printed the “self.lists_selected” and i got “1,2,3,4” as the
result

I thought this would do my job
I am wondering why ‘nil’ is stored in the table.
Please help me out off this guys.

Because your attr_accessor overwrote the accessor which saves to a
database column with one that saves to an instance variable

Thanks again Fred to make me try this out…
I got it after analysing ur reply further

So the trick is not to add a attr_accessor for lists_selected

Regards,
Vimal Das

vimal wrote:

So, is there anyother way to carry this out of the box

I’m not sure precisely what you’re trying to accomplish here, but from
what I can tell it would probably be a lot simpler and more flexible to
use the built-in serialization provided by ActiveRecord:


serialize(attr_name, class_name = Object)

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.

Parameters:
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

Using this technique you can save you Array object to a string field and
get back an Array object automatically. All you have to do is add the
serialize line in your model as shown above.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs