在 rails 应用程序中管理多个域错误:"NameError (uninitialized constant #<Class:0x0000563d7bf62250>::Heroku):"



在我的rails应用程序中,我正在尝试创建一个预订表格,外部方(parks(可以将其客户指向该表格,以便为各自的公园进行预订。预订表格与子域book的url/路线配合使用

https://book.myapp.com/en/parks/:park_id/park_availability

目标

我想用park的网站代替我的域名(myapp.com(,这样我就可以获得

https://book.parkapp.com/en/park_availability

很遗憾,我收到错误消息创建园区

NameError (uninitialized constant #<Class:0x0000563d7bf62250>::Heroku):

使用现有停车场时

{park.website}'s server IP address could not be found.

概述尝试的方法

  1. Park有一个website列。在routes.rb中,我尝试设置约束并将它们应用于park_availability操作
  2. Park模型中,我尝试在保存园区后将域(Park.website(添加到我的Heroku应用程序中
  3. 在我的Park controller中,我试图在park_availability操作之前找到@park

代码

routes.rb

class CustomDomainConstraint
# Implement the .matches? method and pass in the request object
def self.matches? request
matching_site?(request)
end
def self.matching_site? request
# handle the case of the user's domain being either www. or a root domain with one query
if request.subdomain == 'www'
req = request.host[4..-1]
else
req = request.host
end
# first test if there exists a Site with a domain which matches the request,
# if not, check the subdomain. If none are found, the the 'match' will not match anything
Park.where(:website => req).any?
end
end
Rails.application.routes.draw do
resources :parks do
match ':website/park_availability' =>  'parks#park_availability', on: :member, :constraints => CustomDomainConstraint, via: :all
end
end

park.rb

class Park < ApplicationRecord
after_save do |park|
heroku_environments = %w(production staging)
if park.website && (heroku_environments.include? Rails.env)
added = false
heroku = Heroku::API.new(api_key: ENV['HEROKU_API_KEY'])
heroku.get_domains(ENV['APP_NAME']).data[:body].each do |domain|
added = true if domain['domain'] == park.website
end
unless added
heroku.post_domain(ENV['APP_NAME'], park.website)
heroku.post_domain(ENV['APP_NAME'], "www.#{park.website}")
end
end
end

parks_controller.rb

class ParksController < ApplicationController
before_action :find_park, only:[:park_availability]
def park_availability
#working code...
end
private
def find_park
# generalise away the potential www. or root variants of the domain name
if request.subdomain == 'www'
req = request.host[4..-1]
else
req = request.host
end
# test if there exists a Park with the requested domain,
@park = Park.find_by(website: req)
# if a matching site wasn't found, redirect the user to the www.<website>
redirect_to :back
end
end

为了避免出现错误,您可以尝试将类名写为::Heroku,这将使ruby能够在正确的范围内查找它。

但是Heroku的遗留api已经被禁用,所以你应该使用他们的新平台api:

heroku = PlatformAPI.connect(ENV['HEROKU_API_KEY']) # note that you may also have to use a new key
domains = heroku.domain.list(ENV['APP_NAME'])
...
heroku.domain.create(ENV['APP_NAME'], ...)

为了检查域是否存在,您可以使用domain.infoapi方法,而不是获取所有不需要的域。

请记住,回调并不是进行任何外部调用的最佳场所:如果api调用因某种原因(临时网络问题、api中断、服务器重启等(失败,则整个事务将被回滚,项目将不会保存,您可以松散数据。更好的方法是将后台作业排入队列,稍后将处理域,如果需要,可以重试,以此类推

相关内容

  • 没有找到相关文章

最新更新