繁体   English   中英

如何在保存Rails 4之前检查现有记录?

[英]How to check existing record before saving in Rails 4?

我目前正在开发一个简单的Rails 4应用程序,我有两个相关的模型:

book.rb

class Book < ActiveRecord::Base
  belongs_to :author

  accepts_nested_attributes_for :author
end

author.rb

class Author < ActiveRecord::Base
  has_many :books
end

我需要做的是检查作者是否已经存在,如果存在,请在书上使用它。

我的books_controller.rb

class BooksController < ApplicationController
  .
  .
  .
  def create
    @book = Book.new(BookParams.build(params)) # Uses class for strong params 

    if @book.save
      redirect_to @book, notice: t('alerts.success')
    else
      render action: 'new'
    end
  end
end

有没有更好的方法来处理这种情况而没有重复的作者记录? 谢谢。

您可以使用Book模型中的before_save回调来执行此操作:

class Book < ActiveRecord::Base
  # ...

  before_save :merge_author

  private

  def merge_author
    if (author = Author.find_by(name: self.author.name))
      self.author = author
    end
  end
end

请注意,我在此假设您的Author模型具有标识每个作者的name字段。 也许您想要另一种机制来确定作者是否已经存在。

但是, Active Record Validations还可以帮助您确保Author模型中没有重复记录。

我可能会误解,但请尝试更多地解决问题。

从我的角度来看,你必须确保自己没有重复的记录。 在Rails中,您可以在这种情况下使用Validations。

Rails指南验证

另一方面,您尝试解决的问题类似于通过ActiveRecord关联构建/创建ActiveRecord对象。 你也有一个Rails方式。

Rails指南协会

接下来是回调,嵌套路由/控制器aso,以满足不同的要求。 你也可以找到它们的Rails指南。 当然它可以是所有东西的组合=)而且你也有嵌套属性,可能需要考虑。 干杯

我已成功使用以下代码使其工作:

models/book.rb

def author_attributes=(value)
  self.author = Author.find_or_create_by(value)
end

暂无
暂无

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

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