[英]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.