Create attributes in runtime

kostyantyn edited this page Sep 12, 2012 · 2 revisions

Create attributes

Product.hydra_attributes.create(name: 'color', backend_type: 'string', default_value: 'green')
Product.hydra_attributes.create(name: 'title', backend_type: 'string')
Product.hydra_attributes.create(name: 'total', backend_type: 'integer', default_value: 1)
Product.hydra_attributes.create(name: 'price', backend_type: 'float')

Now, all Product instances respond to color, title, total and price attributes.

Product.new
#<Product id: nil, hydra_set_id: nil, created_at: nil, updated_at: nil, color: "green", title: nil, price: nil, color: "green", title: nil, total: 1>  

Creating method accepts the following options:

  • name. The required parameter. Any string is allowed.

  • backend_type. The required parameter. One of the following strings is allowed: string, text, integer, float, boolean and datetime.

  • default_value. The optional parameter. Any value is allowed. nil is default.

  • white_list. The optional parameter. Should be true or flase. false is default. If white_list: true is passed, this attribute will be added to white list and will be allowed for mass-assignment. This parameter is in black list for creation by default so if you want to pass it, you have to pass the role as: :admin too.

      Product.hydra_attributes.create({name: 'title', backend_type: 'string', white_list: true}, as: :admin)