【问题标题】:remote: true Ajax call works in local server but not in Heroku远程:真正的 Ajax 调用在本地服务器中有效,但在 Heroku 中无效
【发布时间】:2015-07-03 08:27:21
【问题描述】:

这是我对 Stack Overflow 的第一个问题。

我正在编写一个将在 Heroku 中运行的 Rails 应用程序。用户可以喜欢/不喜欢帖子。此操作由推荐 gem 的 Sidekiq 工作人员注册。

我正在使用 Public Activity 来跟踪帖子的活动,因此 a.trackable.id 是 post.id...

我在 localhost 中的以下代码中有 ajax 调用:

public_activity/posts/_create.html.erb:

<%= link_to "Beğenmekten Vazgeç", unlike_post_path(a.trackable.id), data: {id: a.trackable.id, toggle_text: 'Beğen', toggle_href: like_post_path(a.trackable.id)}, class: 'like_toggle', remote: true %>

在我的帖子控制器中:

def like
  @post = Post.find(params[:id])
    current_user.like(@post)

  if request.xhr?
    render json: { id: @post.id }
  else
    redirect_to user_profile_path(@post.user)
    flash[:notice] = "Ajax hatası"
  end
end

而 _create.coffee 文件是

$(document).on 'ajax:success', 'a.like_toggle', (status, data, xhr) ->
  $("a.like_toggle[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.text()
    $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    return

本质上,它会更改this 问题中描述的喜欢/不喜欢文本。

在我的 gemfile 中,我有

gem 'jquery-rails', '~> 4.0.3'

在我的 application.js 文件中,我有;

//= require jquery
//= require jquery_ujs
//= require jquery-ui

我在生产环境中清理并预编译了资产。

在 localhost 中运行正常。但是在 Heroku 中,我似乎无法让它工作。

这是服务器日志:

Processing by PostsController#like as HTML 
Parameters: {"id"=>"1"}
User Load (1.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
Post Load (1.6ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1  [["id", 1]]
Redirected to https://emoportal.herokuapp.com/user_profiles/1
2015-04-24T16:14:15.287Z 3 TID-osdy24n1g Recommendable::Workers::Sidekiq JID-986cd2fea4f7bfffd55849b0 INFO: start
2015-04-24T16:14:15.368Z 3 TID-osdy24n1g Recommendable::Workers::Sidekiq JID-986cd2fea4f7bfffd55849b0 INFO: done: 0.082 sec
User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
Completed 302 Found in 680ms (ActiveRecord: 6.7ms)

任何帮助或想法将不胜感激。 谢谢。

【问题讨论】:

  • 你重启 Heroku 了吗? (之前有问题)
  • 你的 Gemfile 中有没有这个:gem 'rails_12factor', group: :production
  • 是的,我愿意。和你写的完全一样。

标签: jquery ruby-on-rails ruby ajax heroku


【解决方案1】:

解决了。问题是 jquery_ujs 在 Heroku 环境中不存在,尽管有所有预编译和其他东西。

在 config/environments/production.rb 文件中,我设置了 config.serve_static_files = true 并设置了 RAILS_ENV=production rake assets:precompile 然后推送到 Heroku 的 repo。

就是这样。

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 2017-03-26
    • 2015-07-08
    • 2017-08-16
    • 2017-11-27
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多