我目前正在开发一个简单的 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
模型中没有重复的记录。
关于ruby-on-rails - 在 Rails 4 中保存之前如何检查现有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21809996/