gilles
gilles

Reputation: 97

How to create dynamic models in Rails?

First, I'm very new to Rails, I have a rather basic questions concerning models.

I have an Event model with a has_many attributes called Properties. I generated my Property model but the attributes have to be defined, however, properties can change according to the event.

Example:

How can I create a Property model with "dynamic" attributes?

Thanks for the help.

Ps: I'm using SQLite

Upvotes: 1

Views: 1206

Answers (2)

Simple Lime
Simple Lime

Reputation: 11035

As mentioned, postgreql has JSON built in, but if you're using any other database, you can set your model up with serialization like so

class Event < ApplicationRecord
  serialize :property, JSON
end

and then get the parsing/saving done automagically for you, no need to clutter your code doing it on your own

Event.create(name: 'Famous Person Concert Thing', property: { artist: 'Someone famous, most likely', kids_allowed: false })                            
#  SQL (0.2ms)  INSERT INTO "events" ("name", "property", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "Famous Person Concert Thing"], ["property", "{\"artist\":\"Someone famous, most likely\",\"kids_allowed\":false}"], ["created_at", "2017-07-15 18:47:05.949921"], ["updated_at", "2017-07-15 18:47:05.949921"]]

Event.last.property
# => {"artist"=>"Someone famous, most likely", "kids_allowed"=>false}

Upvotes: 3

Niklas
Niklas

Reputation: 298

You can store your data as a serialized hash in a string column in sqlite. This way you are more flexible with the kind of data you store. For more native support of json columns you should think about using postgresql.

Parsing and saving hashes with sqlite

Upvotes: 0

Related Questions