Using before_create in Rails to normalize a many to many table

Posted by weotch on Stack Overflow See other posts from Stack Overflow or by weotch
Published on 2010-12-29T04:44:25Z Indexed on 2010/12/29 4:54 UTC
Read the original article Hit count: 195

Filed under:

I am working on a pretty standard tagging implementation for a table of recipes. There is a many to many relationship between recipes and tags so the tags table will be normalized. Here are my models:

class Recipe < ActiveRecord::Base
    has_many :tag_joins, :as => :parent
    has_many :tags, :through => :tag_joins
end

class TagJoin < ActiveRecord::Base
    belongs_to :parent, :polymorphic => true
    belongs_to :tag, :counter_cache => :usage_count
end

class Tag < ActiveRecord::Base
    has_many :tag_joins, :as => :parent
    has_many :recipes, :through => :tag_joins, :source => :parent
        , :source_type => 'Recipe'


    before_create :normalizeTable
    def normalizeTable
        t = Tag.find_by_name(self.name)
        if (t) 
            j = TagJoin.new
            j.parent_type = self.tag_joins.parent_type
            j.parent_id = self.tag_joins.parent_id
            j.tag_id = t.id
            return false
        end
    end
end

The last bit, the before_create callback, is what I'm trying to get working. My goal is if there is an attempt to create a new tag with the same name as one already in the table, only a single row in the join table is produced, using the existing row in tags. Currently the code dies with:

undefined method `parent_type' for #<Class:0x102f5ce38>

Any suggestions?

© Stack Overflow or respective owner

Related posts about ruby-on-rails