ruby on rails许多验证

时间:2016-03-08 13:30:05

标签: ruby-on-rails ruby validation

我有:

scaffold attendance event:references user:references attendance_rate:references
scaffold user name email
scaffold event start_time end_time
scaffold attendance_rate rate:integer #)[1 or 0], i do not want to use boolean)

社团:

event has_many :attendances
attendance belongs_to :event

user has_many :attendances
attendance belongs_to :user

问题:如何允许同一个用户只参加同一个活动一次?

Attendance.rb:

class Attendance < ActiveRecord::Base
  belongs_to :user
  belongs_to :attendance_rate
  belongs_to :event
  validates :user_id, :attendance_rate_id, presence: true
  validates_uniqueness_of :event_id, :scope => [:user_id]
end

注意:出席事件是以事件的嵌套形式创建的。

1 个答案:

答案 0 :(得分:0)

我会使用uniqueness选项进行scope验证。这就像是,

validates_uniqueness_of :event_id, :scope => [:user_id]模型中的

Attendance