Rails 4 JQuery Ajax没有显示出来

时间:2014-08-15 04:30:53

标签: javascript jquery ruby-on-rails ajax

我创建的thing对象没有出现在使用jQuery / Ajax的视图中。

我想在这里附加div标记的东西 index.html.erb

<h1>Listing things</h1>
<%= link_to 'New Thing', new_thing_path, id: "new_thing_link", remote: true %><br>

    <% @things.each do |thing| %>
      <div class="things">
        <%= thing.user_name %>
        <%= thing.topic %>
        <%= thing.truth %>

        <%= link_to 'Show', thing %>
        <%= link_to 'Edit', edit_thing_path(thing) %>
        <%= link_to 'Destroy', thing, method: :delete, data: { confirm: 'Are you sure?' } %><br><br>
      </div>    
    <% end %>
<br>

所以在控制器中我有js formate响应这个自定义模板。前两个步骤按预期工作,我从服务器输出中得到200 OK。

create.js.erb

$(".actions").remove(); // remove the form
$("#new_thing_link").show(); //show the new link again
$('.things').append('<%= j render @thing %>'); //insert the new task into the index template

_create.html.erb

<tr id="topics">
    <td><%= thing.user_name %> |</td>
    <td><%= thing.topic %> |</td>
    <td><%= thing.truth %></td>
</tr>

things_controller.rb

def create
    @thing = Thing.new(thing_params)

    respond_to do |format|
      if @thing.save
        format.html { redirect_to things_url, notice: 'your posting was added.' }
        format.js 
      else
        format.html { render :new }
        format.json { render json: @thing.errors, status: :unprocessable_entity }
      end
    end
  end

但是当我刷新页面时,新的div才显示出来。当我查看源而不刷新页面并且控制台没有显示任何错误时,它就在那里。

这是服务器输出,所以我知道正在创建记录,

Started POST "/things" for 127.0.0.1 at 2014-08-14 21:28:43 -0700
Processing by ThingsController#create as JS
  Parameters: {"utf8"=>"✓", "thing"=>{"user_name"=>"reggie", "truth"=>"it was difficult", "topic"=>"a topic"}, "commit"=>"Create Thing"}
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "things" ("created_at", "topic", "truth", "updated_at", "user_name") VALUES (?, ?, ?, ?, ?)  [["created_at", "2014-08-15 04:28:43.501567"], ["topic", ""], ["truth", "asdf"], ["updated_at", "2014-08-15 04:28:43.501567"], ["user_name", "asdfasd"]]
   (9.0ms)  commit transaction
  Rendered things/_thing.html.erb (0.1ms)
  Rendered things/create.js.erb (2.2ms)
Completed 200 OK in 18ms (Views: 5.7ms | ActiveRecord: 9.6ms)

视图没有像我预期的那样更新。我究竟做错了什么?这是一个涡轮机问题吗?

1 个答案:

答案 0 :(得分:1)

看起来您正确使用它。尝试这个小小的改动,指定你的部分位置(注意你的部分路径可能是错误的,因为我不知道你是如何组织的):

$('.things').append("<%= j render :partial => 'things/create', :locals => {:thing => @thing} %>");