Question

I'd like to do this on Ruby's Datamapper:

Create a table, then execute an SQL statement (raw) after. My DB right now is SQLite. I checked out http://datamapper.org/docs/callbacks.html but it doesn't have anything on adding a callback after the table is constructed. I'm saying this because I need to add a constraint directly or something like an alter table after all of my tables have been generated. The constraint is a unique_index over multiple keys from another table. Something like this:

class Score
belongs_to :pageant, :unique_index => :single_score
belongs_to :candidate, :unique_index => :single_score
belongs_to :category, :unique_index => :single_score
belongs_to :judge, :unique_index => :single_score
end

Anyway what I want to happen is that each pageant-candidate-category-judge combination should be unique. The :unique_index thing doesn't work unless I include another field that isn't linked to another table. So I just thought of adding a constraint via raw SQL (which I would be doing if I wasn't using an ORM).

Was it helpful?

Solution

I just solved this by creating a custom validation. Silly me.

validates_with_method :check_uniqueness_of_score

def check_uniqueness_of_score
    !(Score.all(pageant_id: self.pageant_id, candidate_id: self.candidate_id, 
        category_id: self.category_id, judge_id: self.judge_id).count > 0)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top