【问题标题】:trying to render a partial from click on rails 4, getting 500 (Internal Server Error)尝试通过单击 rails 4 渲染部分内容,得到 500(内部服务器错误)
【发布时间】:2014-08-17 18:51:52
【问题描述】:

我查看了如何在 Rails 4 中渲染部分内容,但遇到了一些问题。我希望在单击链接时呈现表单,但在遵循一些指示后,我收到 500 内部服务器错误。

这是我与遥控器的链接代码:true

<%= link_to "Lostings", new_losting_path, remote: true, id: "lostings_span" %>

这是我的控制器,带有适当的路由/路径

def new # dont need this later
  @losting = Losting.new
  respond_to do |format|
   format.json
  end
end

这是我的 new.js.erb 文件

     $("#asset_nav").prepend('<%= escape_javascript(render "new") %>');

最后是我想要展示的部分表单

 <div class="container"> 
 <h3>Lost</h3>
 <%= form_for @losting, remote: true, html: {multipart: true} do |f| %>
 <%= f.label :pet_name, "Pet name:" %>
 <%= f.text_field :pet_name %>
 <%= f.submit %>
<% end %>
</div>

当我单击链接时,我收到此错误。

GET http://localhost:3000/lostings/new 500 (Internal Server Error) 

出了什么问题,我需要做什么才能正确渲染局部?

【问题讨论】:

  • 服务器日志说什么?你的“新”模板是部分的吗?该文件应命名为_new(以下划线开头)。

标签: ruby-on-rails ajax ruby-on-rails-4 partial


【解决方案1】:

Ajax

据我所知,您遇到的主要问题是您错误地处理了ajax 调用

最好的方法是渲染纯 HTML,然后在 JS 中捕获它:

#app/controllers/lostings_controller.rb
Class LostingsController < ApplicationController

   layout Proc.new { |controller| controller.request.xhr? false : "application" }

   def new
      @losting = Losting.new #-> will load the /views/new.html.erb template
   end
end

这将使您能够将纯 HTML 附加到您的 JS(使用 Rails ajax UJS callbacks):

#app/assets/javascripts/application.js
$("#lostings_span").on("ajax:success", function(data, status, xhr){
   $("#asset_nav").prepend(data);
});

这将使您能够附加从您的 ajax 请求返回的数据。问题是如果您想在前端附加直接 html

【讨论】:

    猜你喜欢
    • 2014-08-05
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2011-11-03
    • 2014-12-26
    • 2015-02-05
    • 1970-01-01
    相关资源
    最近更新 更多