Shrolox
Shrolox

Reputation: 663

Rails - Class treated as Activerecord::Module

I have a class Meal which as a relation with its Type I created a scope in the latter like :

class Type < ActiveRecord::Base
    has_many :meals
    scope :dessert, -> { where(name: "dessert") }
end

and in Meal i'm trying to get the meals that have a dessert Type:

class Meal < ActiveRecord::Base
    belongs_to :type
    scope :dessert, -> { joins(:type).merge(Type.dessert) }
end

When I just do Type.dessert, I get the right result But when I type Meal.dessert, the console gives me this error:

NoMethodError: undefined method `dessert' for ActiveRecord::Type:Module

For me, this error should at least say that Type is a Class as if I type an unexisting function:

NoMethodError: undefined method `toto' for Type (call 'Type.connection' to establish a connection):Class

Can anyone help me to resolve this error ?

Upvotes: 0

Views: 211

Answers (1)

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24551

You can say ::Type.dessert to un-confuse Ruby.

But in my opinion you will save yourself a lot of trouble by renaming your model to MealType. Anyway "type" is so generic it is not a very helpful name. You will probably also wind up with UserType, MenuType, RestaurantType, SubscriptionType, and on and on. It is as bad as having a model named Group. . . .

Upvotes: 3

Related Questions