Ruby on Rails Plugin-based Creator and Updater Model Relationships
Leonhart was nice enough to post about how easy it is to create a Ruby on Rails plugin. The post described how to create a plugin to help with user creator and updater relationships. One of my colleagues decided to try it. A few days later, he noticed issues with RSpec tests that were doing simple things like user.projects and sent me an email to see if I could spot anything.
After spending some time this morning wondering why the RSpec tests were acting really strangely, I tracked down the issue to this section of code in a lib module:
belongs_to :creator, :foreign_key => "created_by", :class_name => "User"
belongs_to :updator, :foreign_key => "updated_by", :class_name => "User"
User.class_eval "has_many: #{self.to_s.tableize}, :foreign_key => :created_by"
One quick note before you use this in the future: Make sure you have Creator and Updater models/classes that extend User, and use them to establish the relationship with the target model. Otherwise, you’ll be wondering why method calls like user.projects returns the projects that a user created instead of the user’s projects!
belongs_to :creator, :foreign_key => "created_by"
belongs_to :updater, :foreign_key => "updated_by"
Creator.class_eval "has_many: #{self.to_s.tableize}, :foreign_key => :created_by"
Updater.class_eval "has_many: #{self.to_s.tableize}, :foreign_key => :updated_by"