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指南。当然,它可以是所有东西的组合=) 而且您也可能需要考虑嵌套属性。我已经成功的欢呼声

相关问题