[英]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
模型中没有重复记录。
我已成功使用以下代码使其工作:
models/book.rb
def author_attributes=(value)
self.author = Author.find_or_create_by(value)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.