My friend helped me to do some cleanup – but it doesn’t look much like rails active record way.
first i wrote this way:
@count_users_approved = current_agent.users.map { |u| u.orders.where("created_at >= ? AND order_status_id = ?", DateTime.now.beginning_of_day, "3")}.count
# rather counting the records, the result was displaying in this way : [0,0,1]
My friend fixed it by writing it in this way:
@count_users_approved = Order.where("created_at >= ? AND user_id IN (?) AND order_status_id = ?", DateTime.now.beginning_of_day, current_agent.users.map(&:id), 2).count
can we write this much cleaner and ActiveRocord type ?
This is how my models are designed.
class Agent < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :agent
has_many :orders
has_many :support_histories
has_one :card_info
end
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :order_type
belongs_to :order_status
end
I’d go this way :
You’re joining the user table to test that the user is assigned to the current agent.
Also there’s no need to map for ids, you could have just passed the
current_agent.usersarray, Rails extracts ids of objects for you when building the query.