DoubleRenderError in Ruby on rails



Getting AbstractController::DoubleRenderError on rendering success message。有人能说出这里出了什么问题吗。

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

结束

在Rails中,在Controller方法/操作中只允许调用render一次。由于该功能可归结为

users = User.all
users.each do |user|
render json: response
end

User.all包含多个用户时(大多数情况下(,它会多次命中render函数。您只能通过互联网发送一个请求响应。您可以考虑使用User.find/find_by确定User.all调用的范围。如果这是不可接受的,并且您确实希望对数据库中的每个用户都这样做,您可以将他们的所有状态收集到一个数组中,并将其作为消息或错误列表发送回。

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

显然,如何执行完全取决于您的需要。

最新更新