【问题标题】:Rails Model Validation using UnlessRails 模型验证使用除非
【发布时间】:2015-01-07 08:07:10
【问题描述】:

我有以下模型订阅类

create_table "subscriptions", force: true do |t|
    t.integer  "user_id"
    t.integer  "course_id"
    t.datetime "date_subscription_start"
    t.datetime "date_subscription_end"
    t.string   "subscription_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我想让用户能够再次订阅同一个课程,如果他们出于某种原因想要重新学习它。我的逻辑是,如果课程/用户组合的 date_subscription_end 日期在新创建时已经过去,则应该只能注册课程。如果在创建时存在具有相同 user_id 和 course_id 且订阅结束日期在未来的订阅,则它应该被拒绝,因为这意味着用户仍在学习该课程。

所以是这样的:

validates :user_id,
  uniqueness: {
    scope: :course_id,
    message: "User is already subscribed to this course"
  },
  unless: Proc.new { |a|
   Subscription.where(user_id: a.user_id, course_id: a.course_id) &&
     Subscription.where('date_subscription_end < ?', Time.now)
  }

基本上,rails 必须遍历订阅表,找到所有具有相同主键的订阅并检查它们的 date_subscription_end 属性。我觉得我很接近但缺少一些基本的东西。

谢谢! 让

编辑:出于某种原因,“你好!”帖子顶部的问候语被删除

【问题讨论】:

标签: ruby-on-rails validation model proc


【解决方案1】:

首先,Proc 看起来不正确,据我所知,只要用户订阅并且 一些 用户(不一定是 a.user_id)订阅了 Proc,它就会返回一个真实值任何课程(不一定是a.course_id

其次,unless 需要是 if 并且是用于唯一性验证的选项哈希的一部分。

所以下面的代码应该可以工作:

validates :user_id,
  uniqueness: {
    scope: :course_id,
    message: "User is already subscribed to this course",
    if: Proc.new { |a|
      Subscription.where(user_id: a.usr_id, course_id: a.course_id)
        .where('date_subscription_end >= ?', Time.now).exists?
    }
  }

这样您只需访问数据库一次,您的代码就不需要像运行 .where(…) 那样实例化所有匹配的订阅

更新

date_subscription_end 的条件应该是:'date_subscription_end &gt;= ?', Time.now

【讨论】:

  • 嗨 jigfox,感谢您的回复,它仍然不完全适合我。当我创建第一个订阅时,给它 Time.now 的 date_subscription_end,然后是 Time.now + 1.days 的第二个订阅(这是正确的),但是现在如果我用 Time.now + 10.days 创建第三个订阅一个还保存...它不应该因为 date_subscription_end of Time.now + 1.day 的订阅仍然有效。
  • 我认为如果将除非更改为 if,上述答案是正确的。当前版本会识别已经存在的记录,并且如果其中一个具有 date_subscription_end > Time.now 它不强制执行验证,这与预期的完全相反。我用 if 对其进行了测试,它似乎工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多