Wednesday 18 May 2011

Sinatra/ActiveRecord Delegate Method Missing Error

I was doing delegation through multiple models earlier

class Model1 < ActiveRecord::Base
#model relationships

delegate :name, :to => :model2, :prefix => true
end

class Model2 < ActiveRecord::Base
#model relationships

delegate :name, :to => :model3, :prefix => false
end

class Model3 < ActiveRecord::Base
#model relationships
#where we want to access the attribute
end

Sinatra was throwing an error unknown method 'name' for Model2. This is strange since I had already told it to delegate this method to Model3. The problem was that even setting the :prefix to false in Model2 was causing method missing to be thrown. To fix all that was required was to remove the middle prefix making Model2

class Model2 < ActiveRecord::Base
#model relationships

delegate :name, :to => :model3
end

This then fixed the problem. When :prefix is assigned true it will prepend the model name to the accessor, you can specify a different prefix though using a different symbol.

class Model1 < ActiveRecord::Base
#model relationships

delegate :name, :to => :model2, :prefix => :user
end

This will allow you to access the name attribute of Model3 through model1.user_name

No comments:

Post a Comment