[英]How to check existing record before saving in Rails 4?
I'm currently working on a simple Rails 4 app where I have these two related models: 我目前正在开发一个简单的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
What I need to do is to check if the author exists already and if it does, use it on the book. 我需要做的是检查作者是否已经存在,如果存在,请在书上使用它。
My books_controller.rb
我的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
Is there a better way to deal with this scenario without having duplicate author records? 有没有更好的方法来处理这种情况而没有重复的作者记录? Thank you. 谢谢。
You can do this using a before_save
callback in the Book
model: 您可以使用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
Note here that I am assuming here that your Author
model has a name
field which identifies each author. 请注意,我在此假设您的Author
模型具有标识每个作者的name
字段。 Perhaps you want to have another mechanism to determine if the author already exists. 也许您想要另一种机制来确定作者是否已经存在。
However, Active Record Validations can also help you ensure that you have no duplicated records in your Author
model. 但是, Active Record Validations还可以帮助您确保Author
模型中没有重复记录。
I might be misunderstanding but try to clearify the problem a little more please. 我可能会误解,但请尝试更多地解决问题。
From my point of view you have to make sure yourself that you don't have duplicate records. 从我的角度来看,你必须确保自己没有重复的记录。 In Rails you can use Validations in that case. 在Rails中,您可以在这种情况下使用Validations。
Rails Guides Validations Rails指南验证
On the other hand what you are trying to solve looks like building/creating an ActiveRecord object through an ActiveRecord association. 另一方面,您尝试解决的问题类似于通过ActiveRecord关联构建/创建ActiveRecord对象。 You have a Rails way for that, too. 你也有一个Rails方式。
Rails Guides Associations Rails指南协会
Next there a callbacks, nested routes/controllers aso that fit to different requirements. 接下来是回调,嵌套路由/控制器aso,以满足不同的要求。 You find Rails Guides for them, too. 你也可以找到它们的Rails指南。 Of course it can be a combination of everything =) And you have nested attributes as well which might have to be considered. 当然它可以是所有东西的组合=)而且你也有嵌套属性,可能需要考虑。 cheers 干杯
I've managed to make it work by using the code below: 我已成功使用以下代码使其工作:
models/book.rb
def author_attributes=(value)
self.author = Author.find_or_create_by(value)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.