使用Ajax渲染部分集合

时间:2014-09-03 18:54:48

标签: javascript jquery ruby-on-rails ajax

我认为我的javascript工作了,但现在它没有加载内容。只是一个空白区域。我目前在我的create.js.erb

中有这个
$('#pit_form').remove(); //remove form
$('#new_link').show();  //show new link again
$('#pit_index').append("<%= j (render :partial => 'pits/pit', :collection => @pits) %>")

我也在pits_controller中的create action中添加了@pits。

控制器

class PitsController < ApplicationController
  before_action :current_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

def new
  @pit = Pit.new
end

def index
  @pit = Pit.all
  @user = User.find_by(params[:id])
  @pits = Pit.paginate(:page => params[:page]).order('created_at DESC').group_by { |pit| pit.created_at.strftime("%B %Y") }
end




def create
    @pit = current_user.pits.create(pit_params)
    @pits = Pit.paginate(:page => params[:page]).order('created_at DESC').group_by { |pit| pit.created_at.strftime("%B %Y") }  
      respond_to do |format|
        format.html { redirect_to @pit}
        format.js
  end
end



def show
  @pit = Pit.find(params[:id])
end

def edit
end

def update
   @pit = Pit.find(pit_params[:id])
     if @pit.update_attributes(pit_params)
       redirect_to @pit
     end
end

def destroy
  @pit = Pit.find(params[:id])
  @pit.destroy
end


def upvote
  @pit = Pit.find(params[:pit_id])
  @pit.upvote_from current_user
  redirect_to pit_path(@pit)
end

def downvote
  @pit = Pit.find(params[:pit_id])
  @pit.downvote_from current_user
  redirect_to pit_path(@pit)
end


private

def correct_user
    @pit = current_user.pits.find_by_id(params[:id])
    redirect_to root_path if @pit.nil?
  end

def pit_params
    params.require(:pit).permit(:topic, :summary, :image, :video_url, :author, :user_id)
end

end

我的日志说它加载了内容,但只显示了一个空白区域。

日志

Started POST "/pits" for 127.0.0.1 at 2014-09-03 13:43:20 -0500
Processing by PitsController#create as JS
  Parameters: {"utf8"=>"✓", "pit"=>{"topic"=>"test", "author"=>"test", "summary"=>"test", "video_url"=>""}, "commit"=>"Start Pit"}
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "pits" ("author", "created_at", "summary", "topic", "updated_at", "user_id", "video_url") VALUES (?, ?, ?, ?, ?, ?, ?)  [["author", "test"], ["created_at", "2014-09-03 18:43:20.845193"], ["summary", "test"], ["topic", "test"], ["updated_at", "2014-09-03 18:43:20.845193"], ["user_id", 1], ["video_url", ""]]
   (1.2ms)  commit transaction
  Pit Load (0.3ms)  SELECT  "pits".* FROM "pits"   ORDER BY created_at DESC LIMIT 30 OFFSET 0
  Rendered pits/_pit.html.erb (0.0ms)
  Rendered pits/create.js.erb (2.2ms)
Completed 200 OK in 23ms (Views: 5.8ms | ActiveRecord: 2.3ms)

根据我的搜索,似乎将@pits添加到创建操作会解决其他答案,但不是我的。会爱一些帮助。

我的index.html.erb

<div class = "container list-pits", id = "pit_index"> 
  <%= link_to "Add New Pit", new_pit_path, id: "new_link", remote: true, class: "btn btn-default" %>
  <br>
  <br>
  <% @pit.each do |pit| %>

  <div class = "container">
    <div class = "well"> 
       <h3 id="pit-title"><%= link_to pit.topic, pit_path(pit) %></h3>
       <p>by <%= link_to pit.author, '#' %></p>
          <br>
            <p><%= pit.summary %></p>
            <p>Replies (<%= pit.comments.count %>)</p>
          <br>

            <p>Pit Created by: <%= link_to pit.user.name, pit.user %> on <%= pit.created_at %></p>

            <%= link_to "View Pit", pit_path(pit), class: "btn btn-primary" %>
            <%= link_to "Delete Pit", pit_path(pit), remote: true, method: :delete, data: { confirm: 'Are you sure?' }  %>
      </div>
    </div>
      <% end %>
  </div>

_pit.html.erb

&LT;

div class = "container list-pits", id = "pit_index"> 
  <%= link_to "Add New Pit", new_pit_path, id: "new_link", remote: true, class: "btn btn-default" %>
  <br>
  <br>
  <% @pit.each do |pit| %>

  <div class = "container">
    <div class = "well"> 
       <h3 id="pit-title"><%= link_to pit.topic, pit_path(pit) %></h3>
       <p>by <%= link_to pit.author, '#' %></p>
          <br>
            <p><%= pit.summary %></p>
            <p>Replies (<%= pit.comments.count %>)</p>
          <br>

            <p>Pit Created by: <%= link_to pit.user.name, pit.user %> on <%= pit.created_at %></p>

            <%= link_to "View Pit", pit_path(pit), class: "btn btn-primary" %>
            <%= link_to "Delete Pit", pit_path(pit), remote: true, method: :delete, data: { confirm: 'Are you sure?' }  %>
      </div>
    </div>
      <% end %>


 </div>

根据一些建议,我在我的_pit部分中抛出了相同的内容。感谢。

2 个答案:

答案 0 :(得分:1)

<强>集合

为了给你一些进一步的范围,collection帮助partial参数基本上取代.each的{​​{1}}方面。重要的一点是,您需要记下要呼叫的本地对象with the as: argument

  

要在partial中使用自定义局部变量名,请指定   :作为调用partial的选项:

     

partial

     

通过此更改,您可以访问@products的实例   集合作为部分内的项局部变量。

这意味着如果您使用<%= render partial: "product", collection: @products, as: :item %>渲染部分内容,则需要确保它具有相邻的collection方法,以便为您提供正确的本地变量名称。此外,正如他在答案中概述的as:,您应该只使用集合数据的Ruby Racer参数:

collection

这会加载#app/views/pits/create.js.erb $('#pit_index').append("<%= j (render :partial => 'pits/pit', collection: @pits, as: :pit) %>") 部分,就像您调用pit一样,这意味着您将能够使用以下内容:

@pits.each do |pit|

<强>修正

您有几个问题(我已在上面解决过),即您在部分内部使用#app/views/pits/_pit.html.erb <div class = "container list-pits", id = "pit_index"> <div class = "container"> <div class = "well"> <h3 id="pit-title"><%= link_to pit.topic, pit_path(pit) %></h3> <p>by <%= link_to pit.author, '#' %></p> <br> <p><%= pit.summary %></p> <p>Replies (<%= pit.comments.count %>)</p> <br> <p>Pit Created by: <%= link_to pit.user.name, pit.user %> on <%= pit.created_at %></p> <%= link_to "View Pit", pit_path(pit), class: "btn btn-primary" %> <%= link_to "Delete Pit", pit_path(pit), remote: true, method: :delete, data: { confirm: 'Are you sure?' } %> </div> </div> </div>

@pit是一个实例变量,这意味着它只能在控制器中设置。如果您使用的是partials,那么您将调用 local 变量,这些变量的范围明显不同于@pit vars。

查看您的日志,似乎正在调用@instance,但您使用partial可能只会导致空白。我的建议解决了这个

答案 1 :(得分:0)

您正在使用

render :partial => 'pits/pit', :collection => @pits

如果您熟悉文档,您应该知道这意味着您将使用partial来为集合中的每个对象呈现ONE对象而不是集合。

通用(不是来自您的代码)部分将是:

_pit.html.erb:

name: <%= pit.name %>
surname: <%= pit.surname %>
<%# etcetera %>

现在,如果你想使用包含集合的部分,那么你应该改变你的部分和对它的调用。

更改部分:
将每个@pits(或已粘贴的@pit)更改为pits

更改您调用它的方式(发送局部变量):
render :partial => 'pits/pit', locals: {pits: @pits}

这应该可以解决问题。

更新:

改变这个:

<% @pit.each do |pit| %>

到此:

<% pits.each do |pit| %>

而且:

$('#pit_index').append("<%= j (render :partial => 'pits/pit', :collection => @pits) %>")

对此:

$('#pit_index').append("<%= j (render :partial => 'pits/pit', locals: {pits: @pits}) %>")

<强>更新 你的@pits是数组的哈希值(已使用group_by {})。所以,你应该像这样更改你的部分:

<% pits.each do |current_value, pitarrray| %>
    <%# maybe do some grouping actions here %>
    <% pitarray.each do |pit| %>

不要忘记,循环结束时会有两个<% end %>