I currently have Scene
and Role
models, and a SceneRole
association table joining them:
class Scene < ActiveRecord::Base
has_many :scene_role
has_many :roles, through: :scene_role
end
class Role < ActiveRecord::Base
has_many :scene_role
has_many :scenes, through: :scene_role
end
class SceneRole < ActiveRecord::Base
belongs_to :scene
belongs_to :role
validates_presence_of :scene_id
validates_presence_of :role_id
validates_uniqueness_of :scene, :scope => :role
end
I want to ensure that any same scene-role relationship is unique. But I also want to gracefully handle attempts to add a Role
to a Scene
when the relationship already exists without getting an error: ActiveRecord::RecordInvalid: Validation failed: Scene has already been taken
My test code:
role = Role.new(name: "Big Bossman")
scene = Scene.new(name: "Arena")
scene.roles << role # success
scene.roles << role # Exception
Is it possible to override create
with the behavior of first_or_create
? I believe that would solve my problem. However, if there is a better way to accomplish the same result I'd appreciate any suggestions. Thank you!