【问题标题】:Rails: Check while building/before saving an object if association matching certain condition is there?Rails:在构建/保存对象之前检查是否存在匹配特定条件的关联?
【发布时间】:2014-06-14 05:21:01
【问题描述】:

我有一个名为 Timesheet 的模型,它有很多 TimesheetRows。 TimesheetRow 属于一个工作。

class Timesheet < ActiveRecord::Base
  has_many :timesheet_rows, inverse_of: timesheet
end
class TimesheetRow < ActiveRecord::Base
  belongs_to :timesheet, inverse_of: timesheet_rows
  belongs_to :job
end

在从日志构建时间表对象时,我正在尝试检查与作业对应的 timesheet_row 是否已经构建,如下所示。

timesheet = Timesheet.new()

if timesheet.timesheet_rows.exists?(job_id:n)
  #Do something
else 
  timesheet.timesheet_rows.build(job_id:n)
end

我已经尝试过 .exists?(condition) 、 .find(:all, condition) 、 .find_by_job_id(n) 、 .where(condition) 等。所有查询都来自数据库,因此在这里没有用处。

我已经浏览了几个小时,寻找一些神奇的方法,但找不到任何方法。真的,我只需要遍历所有关联吗?

类似的question

谢谢

【问题讨论】:

  • 为什么不在TimesheetRow 模型中的job_id 上设置uniqueness validation?它适用于您的情况。
  • 在保存时间表时会进行验证检查,对吗?我只想建立时间表而不是保存。

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-4


【解决方案1】:

尝试使用 ruby​​ 的 select 方法,然后检查结果数组是否为空。

if timesheet.timesheet_rows.select { |tr| tr.job_id == n }.empty?
  timesheet.timesheet_rows.build(job_id: n)
else 
  # Do something
end

正如 @Bot 在 cmets 中建议的那样,您也可以使用 any? 而不是 selectempty?

if timesheet.timesheet_rows.any? { |tr| tr.job_id == n }
  # Do something
else 
  timesheet.timesheet_rows.build(job_id: n)
end

【讨论】:

  • 感谢 JKen。现在我看到三个选项 .any?{}、.detect{}.empty?、.select{}.empty? .我喜欢 .any?{}。您可以将其添加到您的答案中吗?
  • 没问题,我很乐意提供帮助。与any? 通话很棒,我将其添加到我的答案中。
猜你喜欢
  • 2022-07-22
  • 2015-03-28
  • 2012-04-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
相关资源
最近更新 更多