Reputation: 8730
scope :created_after, ->(start_time,end_time) { where("start_time > ? and end_time <?", start_time,end_time) }
I want to add if condition if start time present then only start_time
query run if end_time
then its query run
Upvotes: 2
Views: 1197
Reputation: 392
I think created_between
is better name for what you want to do with your created_after
scope.
You can create two helper scopes to filter results using start_time
and end_time
column.
scope :created_after, ->(start_time) do
where("start_time > ?", start_time)
end
scope :created_before, ->(end_time) do
where("end_time < ?", end_time)
end
Then you can combine them in a way you wanted:
scope :created_between, ->(start_time, end_time) do
query = self.all
query = query.created_after(start_time) if start_time
query = query.created_before(end_time) if end_time
query
end
If you execute query giving nil
for any scope argument it will ignore them. For example: created_between(nil, nil)
will result in no additional query.
Upvotes: 3
Reputation: 23671
You can just chain it in the condition
scope :created_after, ->(start_time, end_time) { start_time && end_time && where("start_time > ? and end_time <?", start_time, end_time) }
This will add the where condition only if start_time
and end_time
is present
Upvotes: 2