Nitro and Og, It's all Greek to me

By eerieshadow.
Tags:

Og and Hashes

How can I use a Hash as a property in one of my objects? How do I manually create the template file, and read inputed fields to the Hash of my object? Does the .fill function work?

To create a Hash as a property simply do

class Customer
  property :title, Hash
  # not necesseraly needed, but generally it helps
  def initialize
    @title = Hash.new
    @title['key_a'] = @title['key_b'] = nil
    # or @title[:key_a] = @title[:key_b] = nil # not advised
  end
end

The keys passed to the Hash can be treated either as symbols or single quoted strings without discrimination. Therefore the initialization of the Hash is not mandatory as long as the keys are strings or symbols. If the key is anything else special care must be taken. Fail proof reasons force us to use ‘key_a’ instead of the symbol :key_a

By the way: Hashes are stored in the database as Text fields.

Next step is to manually create a template file with a form for reading fields into the Hash (just in case you do not want to use the scaffolding of Nitro). The main question here is what should the id= and name= fields of a select or input should be?

<input id="customer_title[key_a]" name="title[key_a]" 
value=@customer.title['key_a'] />

It is not so obvious, but the key_a must not be included in single quotes for the id and the name field. Be aware!

As of version 0.24 of Nitro you can fill the objects’ Hash automatically with the read fields. So, in your controller write something like:

def customer_save
  # ...
  customer = Customer[oid]
  request.fill(customer)
  customer.save
  # ...
end

That should do it! Then you can use the hash normally, calling the keys either as symbols or strings, like this:

customer.title[:key_a]
# or preferably
customer.title['key_a']

first
last