This is a question with Rails / ActiveRecord.
I have a model that basically should represent events or performances. Each event has many attributes: the attribution is basically something like "In this case, Person X has the Y role."
I came to the conclusion that the best way to allow the user to edit this data is to provide a free text field that expects a structured format, which I will call a role string:
singer: Elvis Costello, songwriter: Paul McCartney, ...
where I use autocompletion to perform both role names (singer, songwriter ...) and people names. Both roles and people are stored in a database.
To implement this, I created a virtual attribute in the Event model:
def role_string
Everything is fine. All this works very well when the role string is well formed and the associations defined by the role string are checked.
But what if the role string is incorrect? Well, I suppose I can just use regex along with standard validation to validate the format:
validates_format_of :role_string, :with => /(\w+:\s*\w+)(,\s*\w+:\s*\w+)*/
But what if the associations implied by the role string are not valid? For example, what happens if I give the above line of the role and Elvis Costello does not refer to a real person?
I thought that I could use validates_each for the :role_string attribute to search for associations and throw an error if one of the names it names does not match, for example.
My questions are two: firstly, I do not like this approach, because to check the associations I will have to parse the string and look for them, which duplicates what I will do in role_string= , except for actually storing the associations in the database.
Secondly ... how would I indicate that an error occurred while assigning this virtual attribute?