我目前工作的一個簡單的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
有沒有更好的方式來處理這種情況下,無需重複提交記錄?謝謝。這裏
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
場標識每個作者:
是的,名稱字段我們目前在我的模型。我之前在Rails 3.x中使用這種方法,但是在Rails 4中,它會導致重複的作者記錄。我會在一個單獨的腳手架項目上再次進行測試。謝謝。 – Ben