Reputation: 2103
So i do have a User model, on which i need by_posts
method. by_post
is intended to be executed on already browsed users, eg on
users.where(name: "Jack")
I imagine this method as:
self.by_post(condition)
return self if condition.blank?
##something
end
But right know when i return self like this, it returns a class, not a relation. So when i call this method on object such as:
(byebug) users
[]
(byebug) users.class
ActiveRecord::Relation
what i get back after
users.by_post(nil)
is:
(byebug) users
User(id: integer, , username: string, email: string, created_at: datetime, updated_at: datetime etc
How can i make this method return the exact same object it begun with?
Upvotes: 1
Views: 692
Reputation: 141
If you use the self.methodname it will be added the the User as a class method.
User.by_post("jack")
If you want to call it on user instance skip the 'self.'
Like this
def by_post(condition)
return self if condition.blank?
##something
end
Then you can use it like this
user = User.first
user.by_post("jack")
Upvotes: 0
Reputation: 52357
How can i make this method return the exact same object it begun with?
by_post
method operates on the class (User
), not on the relation, thus what you get is actually the "object it begun with" :)
So in order to return a relation from the by_post
method, you'd want to load it:
self.by_post(condition)
return self.all if condition.blank? # self.scoped for Rails 3
##something
end
Upvotes: 2