0

我有一个接受嵌套参数的模型:

class Publication < ActiveRecord::Base
  attr_accessible :authors_attributes, :title

  has_many :authors
  accepts_nested_attributes_for :authors
end

before_create回调中,我想检查是否存在具有相同标题和作者的另一个出版物。回调看起来像这样:

def find_duplicate
  Publication.where(self.instance_values["attributes"].except("id", "created_at",
    "updated_at")).each do |publication|
      if publication.author_names.sort == @authors
        return publication
      end
  end
end

问题是,我不知道如何获得@authors. 我假设我可以以与 类似的方式检索参数self.instance_values["author_attributes"],但结果为零。我还能如何访问参数?

4

1 回答 1

1

You should have 'authors' as an accessor that's built with the has_many. So, instead of @authors, you would simply use 'authors' or 'self.authors' to get the (non persisted) author objects that are about to be created. Try something like:

Publication.where(self.instance_values["attributes"].except("id", "created_at",
    "updated_at")).each do |publication|
      if publication.authors.collect{|a| a.name}.sort == self.authors.collect{|a| a.name}.sort
        return publication
      end
  end

There are likely better more efficient ways to compare author names here, but this is the clearest way to explain and keep with your paradigm.

于 2013-02-05T19:14:15.327 回答