I have a model that accepts nested params:
class Publication < ActiveRecord::Base
attr_accessible :authors_attributes, :title
has_many :authors
accepts_nested_attributes_for :authors
end
In a before_create callback, I want to check if another Publication exists with the same title and authors. The callback would look something like this:
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
The thing is, I have no idea how to get @authors. I’m assuming I can somehow retrieve the params in a similar fashion to self.instance_values["author_attributes"], but that’s turning up as nil. How else might I access the params?
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:
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.