This is a Rails/ActiveRecord question.
I have a model which basically has to represent events or performances. Each event has many attributions: an attribution is basically something like "In this event, Person X had Role Y".
I concluded that the best way to allow a user to edit this data is by providing a free text field which expects a structured format, which I'll call a role string:
singer: Elvis Costello, songwriter: Paul McCartney, ...
where I use autocompletion to complete on both the names of roles (singer, songwriter...) and the names of people. Both roles and people are stored in the database.
To implement this, I created a virtual attribute in the Event model:
def role_string
# assemble a role string from the associations in the model
end
def role_string=(s)
# parse a string in the above role string format,
# look up the People and Events mentioned, and update
# what's in the database
end
This is all fine. The whole thing works quite well, when the role string is well-formed and the associations given by the role string all check out.
But what if the role string is malformed? Okay, I figure, I can just use a regex together with standard validation to check 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 invalid? For example, what happens if I give the above role string, and Elvis Costello
doesn't reference a valid person?
I thought, well, I could use validates_each
on the attribute :role_string
to look up the associations and throw an error if one of the names given doesn't match anything, for example.
My questions are two: first, I don't like this approach, since to validate the associations I would have to parse the string and look them up, which duplicates what I'd be doing in role_string=
itself, except for actually saving the associations to the database.
Second, ... how would I indicate that an error's occurred in assigning to this virtual attribute?