Getting AbstractController::DoubleRenderError on rendering success message. Can anyone tell what is the issue here.
def send_alert
if (params[:community_id].present? )
community = Community.find(params[:community_id])
users = User.all
users.each do |user|
inspector_alert = Alert.where("alert_time >= ?",(Time.now - 10.minutes)).where(user_id: user.id,community_id: community.id)
if inspector_alert.count == 0
send_sms_to_user(user, "Approching your #{community.name}")
render json: {message: "Notification Sent Successfully!"}, status: 200
else
render json: { error: "Notification sent recently, try after sometime"}, status: 403
end
end
elsif (params[:home_id].present? )
users = User.all
home = Home.find(params[:home_id])
if home.community.is_home == true
users.each do |user|
inspector_alert = Alert.where("alert_time >= ?",(Time.now - 10.minutes)).where(user_id: user.id,home_id: home.id)
if inspector_alert.count == 0
send_sms_to_user(user, "Approching your home #{home.name}")
render json: {message: "Notification Sent Successfully!"}, status: 200
else
render json: { error: "Notification sent recently, try after sometime"}, status: 403
end
end
end
end
end
CodePudding user response:
In Rails, you are only permitted to call render
once in a Controller method/action. Since the function boils down to
users = User.all
users.each do |user|
render json: response
end
When User.all
contains more than one user (most of the time), it will hit the render
function more than once. You are only permitted to send one response to a request over the internet. You might consider scoping the User.all
call, using User.find/find_by
. If this isn't acceptable and you do want to do this for each and every User in the database, you could collect all their statuses into an array, and send that back as a list of messages or errors.
def send_alert
messages = []
errors = []
if (params[:community_id].present? )
community = Community.find(params[:community_id])
users = User.all
users.each do |user|
inspector_alert = Alert.where("alert_time >= ?",(Time.now - 10.minutes)).where(user_id: user.id,community_id: community.id)
if inspector_alert.count == 0
send_sms_to_user(user, "Approching your #{community.name}")
# add this message to the pile
messages << "Notification Sent Successfully!"
else
# add this error to the pile
errors << "Notification sent recently, try after sometime"
end
end
elsif ...
end
if errors.size == 0
# no errors, send all the messages to this endpoint
render json: { message: messages ), status: 200
else
# any error, consider this a failure
render json: { error: errors }, status: 403
end
end
Obviously, how this is executed exactly is up to your needs.