Ruby datamapper - 创建表时的回调?

时间:2013-08-28 04:42:45

标签: ruby sinatra ruby-datamapper

我想在Ruby的Datamapper上执行此操作:

创建一个表,然后执行一个SQL语句(raw)。我的DB现在是SQLite。我检查了http://datamapper.org/docs/callbacks.html但是在构造表之后添加回调没有任何内容。我这样说是因为我需要在生成所有表后直接添加约束或类似alter table。约束是来自另一个表的多个键的unique_index。像这样:

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

无论如何,我想要发生的是每个选美候选人 - 类别 - 判断组合应该是唯一的。 :unique_index事情不起作用,除非我包含另一个未链接到另一个表的字段。所以我只想通过原始SQL添加一个约束(如果我没有使用ORM,我会这样做。)

1 个答案:

答案 0 :(得分:1)

我刚刚通过创建自定义验证解决了这个问题。傻我。

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