检查时间重叠的问题

时间:2016-08-05 18:52:34

标签: ruby-on-rails ruby

有两种型号:

# Table name: activities_people
#
#  activity_id :integer          not null
#  person_id   :integer          not null
#  date        :date             not null
#  id          :integer          not null, primary key

# == Schema Information
#
# Table name: activities
#
#  id          :integer          not null, primary key
#  name        :string(20)       not null
#  description :text
#  active      :boolean          not null
#  day_of_week :string(20)       not null
#  start_on    :time             not null
#  end_on      :time             not null

关系: activity.rb

has_many :activities_people
has_many :people, through: :activities_people

activity_people.rb

belongs_to :person
belongs_to :activity

我尝试创建验证,该人可以加入到特定日期和时间(start_on,end_on)中发生的一项活动。如果我在参加其他练习之前尝试注册其他活动(同一日期和时间重叠)应该抛出错误。 我尝试了什么:

  def check_join_client
    activities_date = person.activities_people.where('date = date', date: date)
    if activities_date.exists && person.activities.where('id IN (?)', activities_date)
  end

我不知道如何使用创建查询(person.activities.where ...)来获取与activies_people相关的人员活动。 activities_date检查我们是否参加了同一日期的活动。其次,我想检查start_on和end_on。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

如果我正确理解您,您希望找到与日期数组匹配查询的用户activites_people,然后引发错误,除非相关的activity匹配activities_people

check_join_client的原始代码错误地使用了if

 def check_join_client
    activities_date = person.activities_people.where('date = date', date: date)
    if activities_date.exists && person.activities.where('id IN (?)', activities_date)
  end

要将此转换为伪代码,您实际上是在说:

result = query if result.condition_met?

但是,在定义if之前,将评估if条件(results之后的表达式)。如果我展示出正确的方法,可能会更清楚:

result = query   返回结果如果result.condition_met?

现在回到你关于加载相关记录的问题,尝试这样的事情:

   activities_people_ids_matching_date = person.activities_people
                                               .where(date: self.date)
                                               .pluck(:id)
   # use pluck to get an array of ids because that's all that's needed here
   # not sure how you're getting the date variable, so I'm assuming self.date will work
   # I can use `.any?` to see if the ids list is not empty.
   condition_met = activities_people_ids_matching_date.any? &&\
                   person.activities
                         .where(activities_people_id: activities_people_ids_matching_date)
                         .any?
   condition_met ? true : raise(StandardError, "my error")

肯定有一种方法可以通过一个查询而不是两个查询来完成这项任务,但是看起来您在使用Ruby概念时,关注语法和核心功能比SQL优化更重要。

答案 1 :(得分:0)

正确的语法(几个选项之一)是:

public MemberInfo GetMemberInfo<T>(Expression<Func<T>> memberLambda)
{
    var memberExpression = memberLambda.Body as MemberExpression;

    if (memberExpression == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Member' or '() => object.Member'");
    }

    return memberExpression.Member;
}