简体   繁体   English

Rails:在构建对象时/保存对象之前检查是否存在符合特定条件的关联?

[英]Rails: Check while building/before saving an object if association matching certain condition is there?

I have a model called Timesheet which has many TimesheetRows. 我有一个名为Timesheet的模型,其中有许多TimesheetRows。 TimesheetRow belongs to a job. 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

While building a timesheet object from logs, I am trying to check if timesheet_row corresponding to a job has been already built or not, as follows. 从日志构建时间表对象时,我尝试检查与作业相对应的timesheet_row是否已构建,如下所示。

timesheet = Timesheet.new()

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

I have tried .exists?(condition) , .find(:all, condition) , .find_by_job_id(n) , .where(condition) etc. All query from database, and thus won't be useful here. 我已经尝试过.exists?(condition),.find(:all,condition),.find_by_job_id(n),.where(condition)等。所有从数据库查询,因此在这里将无用。

I have browsed for hours now, looking for some magic method but couldn't find any. 我已经浏览了几个小时,正在寻找一种神奇的方法,但是找不到任何方法。 Really, will I just have to loop through all the associations? 真的,我是否只需要遍历所有关联?

A similar question . 一个类似的问题

Thanks 谢谢

Try using ruby's select method, and then checking if the resulting array is empty. 尝试使用ruby的select方法,然后检查结果数组是否为空。

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

As @Bot suggested in the comments, you can also use the any? 正如@Bot在评论中建议的那样,您还可以使用any? rather than select and empty? 而不是selectempty? .

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM