ruby on rails - Fix inconsistency with polymorphic association -


i have polymorphic association in model , experienced intermittent bug (in production) when created. fixed it, need repair entries created under bug.

my models:

class user < activerecord::base   belongs_to :userable, :polymorphic => true   attr_protected :userable end  class usertype1 < activerecord::base   has_one :user, :as => :userable, :dependent => :destroy end  class usertype2 < activerecord::base   has_one :user, :as => :userable, :dependent => :destroy end 

so, problem have entries on user table without relation polymorphic table.

record example (users table):

id  userable_id userable_type 999 null        usertype1 

and usertype1 hasn't entry related.

so made query detect entry errors:

select users.* users coalesce(userable_id, 0) = 0' 

but don't know how repair cleanly.

my idea create script this:

user.find_by_sql('select users.* users coalesce(userable_id, 0) = 0').each |user|   userable = user.userable_type.classify.constantize.new   userable.user = user   userable.save   user.userable = userable   user.save end 

thanks

class user   alias_method :old_userable, :userable    def userable     old_userable || userable.new   end  end 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -