我有一个 ruby on rails 应用程序,它位于 0.0.0.0:3000 和端口 0.0.0.0:80 上的话语 docker 容器。我想将 localhost RoR 应用程序与 docker 容器绑定,因为 postgreSQL 在 docker 容器内运行,并且希望将 RoR 应用程序与 docker 容器内的 postgreSQL 连接。如何在 RoR 应用程序和 docker 容器 postgrePSQL 之间建立数据库连接。
这是我的 RoR 控制器。
class CronController < ApplicationController
# slack channel hook
$slackHook = "https://hooks.slack.com/services/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"
$discourseHost = 'community.cloudways.com/';
$messageText = "New Notification";
# import http module
require 'net/http'
=begin
A method which build connection with postgreSQL and fetch last 24hr records
=end
def slackNotification
logger.debug "*******Cron Started********"
begin
$query = "SELECT users.username AS username, topics.title AS topic_title, topics.id AS topic_id, posts.raw AS raw FROM post_replies
JOIN posts ON posts.id = post_replies.post_id
JOIN users ON users.id = posts.user_id
JOIN topics ON topics.user_id = users.id
WHERE post_replies.created_at BETWEEN current_date AND current_date - INTERVAL '1' DAY;"
$res = ActiveRecord::Base.connection.exec_query(query);
# iteration on each record
$res.each do |row|
sendNotifications row
end
logger.debug "*******Cron successfully executed.********"
render :json => {:status => "true", :message => "Cron successfully executed."}
rescue Exception => e
logger.fatal "Exception: #{e}"
end
end
=begin
such method which take payload and send it to slack hook url
@params row
=end
def sendNotifications row
$title = row['topic_title']
$topicId = row['topic_id']
$content = row['raw']
begin
uri = URI.parse($slackHook)
# Full control
http = Net::HTTP.new(uri.host, uri.port)
response = Net::HTTP.post_form(uri, {
'payload' => '{
"fallback": "#{$messageText}",
"text": "#{$title}",
"pretext": "<http://#{$discourseHost}|#{$title}>",
"color": "#36a64f",
"fields": [
{
"title": "#{$title}" ,
"value": "#{$content}",
"short": false
}
]
}'
})
rescue Exception => e
logger.fatal " Attributes: title: #{$title}, topicId: #{$topicId}, content: #{$content}, URL: <http://#{$discourseHost}|#{$title}> "
logger.fatal "Exception: #{e}"
end
end
end