【问题标题】:Rails ActiveRecord:: Proper way for validating presence on associations?Rails ActiveRecord:: 验证关联存在的正确方法?
【发布时间】:2014-06-15 02:46:07
【问题描述】:

我在模型 ProjectQueue 之间有一个 Rails 关联。一个项目有多个队列。队列必须有一个项目,因此在 project_id 上有一个存在验证

假设我想创建一个带有队列的新项目。例如,像这样:

project = Project.new(valid: param, options: here)
project.queues << Queue.new(other_valid: param, options: here)
project.save!

保存将失败,因为队列未通过 project_id 存在验证。

我通常的解决这个问题的丑陋方法是创建一个项目,然后添加队列,并将整个批次包装在一个事务中,这样如果流程的任何部分失败,它就会回滚。 ...不知何故,这似乎比它应该的更丑。

那么,有没有一种更优雅的方式来在新项目上创建队列而无需进行存在验证,但仍然断言这些队列必须有一个项目?

干杯

【问题讨论】:

  • 在您的代码中,当将队列分配给 project.queues 时,它应该自动将 project_id 分配给该队列。你确定这会失败吗?

标签: ruby-on-rails activerecord activemodel


【解决方案1】:

尝试在队列关联中使用build 方法,如下所示:

project = Project.new(valid: param, options: here)
project.queues.build(other_valid: param, options: here) //this will build the queue and set its project_id to your current project.
project.save!

只是为了确保您的 project_id 具有正确的值,在调用 project.save! 之前插入此行:

project.queues.each do |queue|
  puts queue.project_id 
end

那么你的代码有什么问题?

project = Project.new(valid: param, options: here) //build a new project - this is not yet persisted, so your id column is nil
project.queues << Queue.new(other_valid: param, options: here) // this line tries to save the queue to the database, does not wait for you to call project.save!
project.save!

当你打电话时:

project.queues << Queue.new(other_valid: param, options: here)`

Rails 尝试将您的新队列保存到数据库,但由于您的项目未保存,queue.project_id 为 nil,因此您的队列验证失败。

如果您尝试对从数据库中提取的项目(持久项目)进行类似操作,您的代码将不会出错。

如果您仍想使用类似的东西,请在添加新队列之前保存项目,如下所示:

project = Project.new(valid: param, options: here)

if project.save
  project.queues << Queue.new(other_valid: param, options: here) //this guarantees that project_id exists
end

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 2011-08-07
    • 2016-11-03
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多