如何修复 Rails 中的 Ember CLI 错误?

How can I fix this Ember CLI error in Rails?

我正在将我的第一个 Ember 应用程序集成到 Rails 项目中。我添加了 ember-cli-rails gem 和 运行 初始化程序,这样我就有了一个 config/initializers/ember.rb 文件,如下所示:

EmberCLI.configure do |c|
  c.app :products, path: 'products'
end

我的 Ember 应用程序位于我的 Rails 应用程序根目录中,名为 products。我现在除了生成默认 Ember 应用程序外什么也没做。

我在 Rails 中为 ProductsController 创建了一个特定的布局。是 app/views/products.html.erb。我添加了以下几行:

<%= include_ember_script_tags :products %>
<%= include_ember_stylesheet_tags :products %>

我还编辑了 Ember 应用程序的 router.js 文件,因为我没有在根 URL 上提供 Ember 应用程序:

var Router = Ember.Router.extend({
  rootURL:  config.baseURL, // added this line
  location: config.locationType
});

最后我在 Ember 应用中更改了 config/environments.js

var ENV = {
  modulePrefix: 'products',
  environment: environment,
  baseURL: '/products', // changed from '/' to '/products'
  locationType: 'auto',
  EmberENV: {
    FEATURES: {
      // Here you can enable experimental features on an ember canary build
      // e.g. 'with-controller': true
    }
  },

该控制器的索引页显示正常。它正在尝试加载 Ember 文件,但我收到错误消息:

Uncaught Error: Assertion Failed: rootURL must end with a trailing forward slash e.g. "/app/"

ember-cli-rails 的说明不包含尾部斜线。

如果我添加尾部斜线,我得到:

Uncaught Error: Assertion Failed: Path /products does not start with the provided rootURL /products/

我意识到我在这里的第一个 Ember 申请中可能遗漏了一些非常基本的东西。非常感谢您提供的任何帮助。

我找到了答案here

因此,继续将尾部斜杠添加到 baseURL。然后按照上面链接的 post 中的说明进行操作,我将在此处进行总结:

class YourEmberAppController

  before_action :ensure_trailing_slash

  respond_to :html, :js

  def index
    render :index
  end

  def vehicles
  end

  def save
  end

  private

  def ensure_trailing_slash
    unless trailing_slash?
      redirect_to url_for(params.merge(trailing_slash: true)), status: 301
    end
  end

  def trailing_slash?
    request.env['REQUEST_URI'].match(/[^\?]+/).to_s.last == '/'
  end

end

执行此操作,您将看到 "Welcome to Ember" 作为页面的一部分。

在 Rails' routes.rb:

get 'products', to: redirect('/products/'), constraints: lambda { |req| req.env['REQUEST_URI'].last != '/' }