Rails:在构建/保存对象之前检查是否存在匹配特定条件的关联



我有一个名为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)等。所有查询都来自数据库,因此在这里不会有用。

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

同样的问题。

谢谢

尝试使用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在评论中建议的那样,您也可以使用any?而不是selectempty?

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

相关内容

最新更新