user814584
user814584

Reputation: 325

Accessing Data inside a hash returned from a database

I'm a PHP developer getting into Ruby on Rails. I'm working on a project where a collection of strings is serialized and stored in a database. I'm trying to access that data, but inside a mailer class I'm writing but am having troubles. Inside the Model where the data is being taken out of the DB, I can access what I need by using email.attr(key,'subject'), however when I pass the email variable to the mailer class and try to use that same method of access inside the mailer class I get an "undefined variable 'key'" error message.

Here is a dump of the data when I run email.inspect.

{"subject"=>"Subject of Email", "intro"=>"Welcome"}

My search results in Google did not return anything helpful.

Upvotes: 1

Views: 759

Answers (1)

Adam
Adam

Reputation: 3158

Typically, you would access data in a hash by doing something like:

email["subject"]

In your case, it looks like the email object has attributes, so it's not a hash but an actual object. In this case, assuming you have an attr_reader for both subject and intro, you would do:

email.subject

However, I think the bug in your above example might be b/c the word 'key' in the method call isn't quoted (hence, it's treating it like a variable). Just a guess though as I've never seen an attribute accessed through an attr method.

Upvotes: 2

Related Questions