Reputation: 509
Is it possible to reuse query methods from different models?
I already have the following model:
class Profile
belongs_to :user
def self.search_by_name(search)
# Some query code...
# Returns Profile::ActiveRecord_Relation
end
end
Now I want to implement a similar method: User.search_by_name
.
class User
has_one :profile
def self.search_by_name(search)
Profile.search_by_name(search).joins(table_name)
# Should return User::ActiveRecord_Relation
end
end
How can I make User.search_by_name to return User::ActiveRecord_Relation
? Current solution is returning Profile::ActiveRecord_Relation
.
Upvotes: 0
Views: 101
Reputation: 392
Use Concerns.
app/models/concerns/query.rb
module Query
extend ActiveSupport::Concern
module ClassMethods
def search_by_name(search)
# Some query code...
end
end
end
Then include Query
in your Profile and User models.
Upvotes: 0
Reputation: 2586
I can only guess what you try to accomplish but I think your looking for merge
class User
has_one :profile
def self.search_by_name(search)
joins(:profile).merge(Profile.search_by_name(search))
end
end
Upvotes: 2