1

我目前工作的一個簡單的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場標識每個作者:

回答

0

,使其通過使用下面的代碼工作:

models/book.rb

def author_attributes=(value) 
    self.author = Author.find_or_create_by(value) 
end 
3

您可以在Book模型使用before_save回調做到這一點。也許你想有另一種機制來確定作者是否已經存在。

然而,Active Record Validations也可以幫助您確保您的Author型號中沒有重複的記錄。

+0

是的,名稱字段我們目前在我的模型。我之前在Rails 3.x中使用這種方法,但是在Rails 4中,它會導致重複的作者記錄。我會在一個單獨的腳手架項目上再次進行測試。謝謝。 – Ben

0

我可能會誤解,但請嘗試再澄清一點問題。

從我的角度來看,您必須確保自己沒有重複的記錄。在Rails中,你可以在這種情況下使用驗證。

Rails Guides Validations

在另一方面你正在試圖解決的模樣建築/通過一個ActiveRecord協會創建一個ActiveRecord對象。你也有Rails的方式。

Rails Guides Associations

接着有一個回調,嵌套路由/控制器ASO適合不同的要求。你也可以找到Rails指南。當然,它可以是所有東西的組合=) 而且您也可能需要考慮嵌套屬性。我已經成功的歡呼聲

相關問題