I'd like to incorporate a step to check for an existing relation object as part of my model creation/form submission process. For example, say I have a Paper
model that has_and_belongs_to_many :authors
. On my "Create Paper" form, I'd like to have a authors_attributes
field for :name
, and then, in my create
method, I'd like to first look up whether this author exists in the "database"; if so, then add that author to the paper's authors
, if not, perform the normal authors_attributes
steps of initializing a new author.
Basically, I'd like to do something like:
# override authors_attributes
def authors_attributes(attrs)
attrs.map!{ |attr| Author.where(attr).first_or_initialize.attributes }
super(attrs)
end
But this doesn't work for a number of reasons (it messes up Mongoid's definition of the method, and you can't include an id
in the _attributes
unless it's already registered with the model).
I know a preferred way of handling these types of situations is to use a "Form Object" (e.g., with Virtus). However, I'm somewhat opposed to this pattern because it requires duplicating field definitions and validations (at least as I understand it).
Is there a simple way to handle this kind of behavior? I feel like it must be a common situation, so I must be missing something...