使用 ajax 成功创建表单后呈现部分内容

Rendering a partial after a successful form create with ajax

我的控制器代码:

class HitChallengesController < ApplicationController

  def create
    game = Game.find(params[:id])
    suite_id = Suite.find_by(suite_number: params[:hit_challenge][:suite_id], game_id: game.id).id
    @hit_challenge = HitChallenge.new(game_id: game.id, suite_id: suite_id, title: params[:hit_challenge][:title])
    if @hit_challenge.save && request.xhr?
      respond_to do |format|
        format.json { render json: @hit_challenge}
      end
    else
      redirect_to games_show_path(game)
    end
  end
end

查看部分:

  <%if @game.has_hit_challenge %>
    <h4>Hit Challenges: </h4>

    <%if @hit_challenges.count > 1%>
      <% @hit_challenges.each do |h|%>
        <li>
        <%= "Suite #{h.suite.suite_number}, #{h.title}:" %>
        <%= link_to "Status", hit_status_path(h) %>
        <%= link_to "Play", play_hit_challenge_path(h) %>
        <%= form_for h, url: delete_hit_challenge_path(h), method: :delete do |f| %>
          <%= f.hidden_field :hit_challenge_id, value: h.id %>
          <%= f.submit "Delete" %>
        <%end%>
        </li>
      <%end%>
    <%else%>
      <li>
      <%= "Suite #{@hit_challenges.first.suite.suite_number}, #{@hit_challenges.first.title}:" %>
      <%= link_to "Status", hit_status_path(@hit_challenges.first) %>
      <%= link_to "Play", play_hit_challenge_path(@hit_challenges.first) %>
      <%= form_for @hit_challenges.first, url: delete_hit_challenge_path(@hit_challenges.first), method: :delete do |f| %>
        <%= f.hidden_field :hit_challenge_id, value: @hit_challenges.first.id %>
        <%= f.submit "Delete" %>
      <%end%>
      </li>
    <%end%>
  <%end%>

视图的其余部分:

<%if is_admin%>
  <div class='create-challenges'>
    <p>
      <%=form_for :suite, url: create_suite_path(:game_id => @game.id) do |f| %>
        <%= f.label 'Suite Number:' %>
        <%= f.text_field :suite_number %>
        <%=f.submit "Create" %>
      <%end%>
    </p>
    <p>
      <%=form_for :pitch_speed , url: create_pitch_speed_path(:game_id => @game.id) do |f|%>
        <%=f.label 'Create Pitch Speed Challenge' %>
        <%=f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
        <%=f.label "Title:" %>
        <%=f.text_field :title %>
        <%=f.label "Min Speed:" %>
        <%=f.text_field :min_speed %>
        <%=f.label "Max Speed:" %>
        <%=f.text_field :max_speed %>
        <%=f.submit 'Create' %>
      <%end%>
    </p>
    <p>
      <%=form_for :prop_bet, url: create_prop_bet_path(:game_id => @game.id) do |f| %>
        <%= f.label 'Create Prop Bet:' %>
        <%= f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
        <%= f.label "Title:" %>
        <%= f.text_field :title %>
        <%=f.submit "Create" %>
      <%end%>
    </p>
    <p>
      <%=form_for :hit_challenge, url: create_hit_challenge_path, :remote => true do |f| %>
        <%= f.label 'Create Hit Challenge:' %>
        <%= f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
        <%= f.label "Title:" %>
        <%= f.text_field :title %>
        <%=f.submit "Create" %>
      <%end%>
    </p>
  </div>
  <%= link_to "Edit Game", games_edit_path(@game) %>
<div class='challenge-lists'>
  <div class='hit-list'>
    <%=render 'hit_challenges_list', locals: {@hit_challenges => @hit_challenges, @game => @game} %>
  </div>
  <div class='prop-list'>
  <%if @game.has_prop_bet%>

    <h4> Prop Bets:</h4>

    <%if @prop_bets.count > 1 %>
      <% @prop_bets.each do |prop| %>
        <li>
          <%= "Suite #{prop.suite.suite_number}, #{prop.title}:" %>
          <%=link_to "Status", prop_status_path(prop) %>
          <%=link_to "Play", show_prop_bet_path(prop) %>
          <%=link_to "Edit", edit_prop_path(prop) %>
          <%= form_for prop, url: delete_prop_bet_path(prop), method: :delete do |f| %>
            <%= f.hidden_field :prop_id, value: prop.id %>
            <%= f.submit "Delete" %>
          <%end%>
        </li>
      <%end%>
    <%else%>
      <li>
      <%="Suite #{@prop_bets.first.suite.suite_number}, #{@prop_bets.first.title}:" %>
      <%= link_to "Status", prop_status_path(@prop_bets.first) %>
      <%= link_to "Play", show_prop_bet_path(@prop_bets.first) %>
      <%=link_to "Edit", edit_prop_path(@prop_bets.first) %>
      <%= form_for @prop_bets.first, url: delete_prop_bet_path(@prop_bets.first), method: :delete do |f| %>
        <%= f.hidden_field :prop_id, value: @prop_bets.first.id %>
        <%= f.submit "Delete" %>
      <%end%>
      </li>
    <%end%>
  <%end%>
  </div>
  <div class='pitch-list'>
    <%if @game.has_pitch_speed %>
      <h4> Pitch Speed Challenges </h4>
      <%if @game.pitch_speeds.count > 1 %>
        <%@pitch_speeds.each do |pitch| %>
          <%= "Suite #{pitch.suite.suite_number}, #{pitch.title}:" %>
          <%=link_to "Play", play_pitch_speed_path(pitch) %>
        <%end%>
      <%else%>
        <%= "Suite #{@game.pitch_speeds.first.suite.suite_number}, #{@game.pitch_speeds.first.title}:" %>
        <%=link_to "Play", play_pitch_speed_path(@game.pitch_speeds.first) %>
      <%end%>
    <%end%>
  </div>
</div>
  <p>
    <li><%= link_to "Add Home Players", add_home_player_path(@game)%></li>
    <li><%= link_to "Add Away Players", add_away_player_path(@game)%></li>
  </p>
  <p>
    Total Hits:
    <%=form_for @game, url: update_game_hits_path do |f| %>
      <%=f.text_field :total_hits%>
      <%=f.submit "Update Hits" %>
    <%end%>
  </p>
<%end%>

最后是我的 js 文件:

$(document).ready(function(){
  $('.create-challenges').on('submit', function(e){
    e.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      method: $(this).attr('method'),
      data: $(this).serialize()
    }).done(function(response){
      data = '<%= j(render partial: "hit_challenges_list")%>';
      console.log(data);
      $(".hit-list li").append(data);

    }).fail(function(){
      console.log('you fail in life')
    })
  })

我正在尝试从该表单创建一个 hit_challenge,然后尝试将其附加到 hit_challenge 列表,如上所示。部分本身工作正常,我可以看到 hit_challenges 正常。

ajax 调用通过,记录已创建,但我无法弄清楚追加部分。我认为在我尝试将新创建的记录数据传递给部分时出现了问题...附加的是'<%= j(render partial: "hit_challenges_list")%>',它就像 ruby 里面的代码不起作用

会不会是我偏分太多了?我尝试在 '<%= j(render partial: "hit_challenges_list")%>' 中传递当地人,但没有任何区别。顺便说一句,我正在使用 rails 4.

编辑:

现在我遇到了一个奇怪的语法错误,我看不出部分有什么问题,我没有改变任何东西,它在那个 js 方法之外工作

SyntaxError (/Users/ddgs89/Desktop/Suite-Success/suite_success/app/views/games/_hit_challenges_list.html.erb:1: 语法错误,意外的 '=',期待 keyword_end ...tput_buffer = @output_buffer; = = local_assigns[:];;@输出... ... ^ /Users/ddgs89/Desktop/Suite-Success/suite_success/app/views/games/_hit_challenges_list.html.erb:1: 语法错误,意外的 ']',应为 tSTRING_CONTENT 或 tSTRING_DBEG 或 tSTRING_DVAR 或 tSTRING_END ...t_buffer; = = local_assigns[:];;@output_buffer = output_buf... ... ^): app/views/games/_hit_challenges_list.html.erb:1: 语法错误,意外的 '=',应为 keyword_end app/views/games/_hit_challenges_list.html.erb:1: 语法错误,意外的 ']',应为 tSTRING_CONTENT 或 tSTRING_DBEG 或 tSTRING_DVAR 或 tSTRING_END app/views/hit_challenges/create.js.erb:9:在_app_views_hit_challenges_create_js_erb___1940717404351023775_70144770896860' app/controllers/hit_challenges_controller.rb:8:in创建'

创建。js.erb

$(document).ready(function(){
  $('.create-challenges').on('submit', function(e){
    e.preventDefault();
    $.ajax({
      url: $(this).attr('action'),
      method: $(this).attr('method'),
      data: $(this).serialize()
    }).done(function(response){
      data = '<%= j(render partial: "games/hit_challenges_list", locals: {@hit_challenges => @hit_challenges, @game => @game})%>';
      console.log(data);
      $(".hit-list li").append(data);

    }).fail(function(){
      console.log('you fail in life')
    })
  })
})

它不起作用,因为您正试图在客户端进行服务器端呈现。一种方法是让您的控制器呈现部分并将其提供给客户端,但更好的方法和 Rails 方法是在 form_fors 上使用 remote: true 选项(不确定您发布的观点是否正确,因为创建挑战 CSS class 不是您发布的形式).

在您的创建操作中,您将拥有:

def create
    game = Game.find(params[:id])
    suite_id = Suite.find_by(suite_number: params[:hit_challenge][:suite_id], game_id: game.id).id
    @hit_challenge = HitChallenge.new(game_id: game.id, suite_id: suite_id, title: params[:hit_challenge][:title])
    if @hit_challenge.save && request.xhr?
      respond_to do |format|
        format.json { render json: @hit_challenge}
        format.js
      end
    else
      redirect_to games_show_path(game)
    end
  end

在你的create.js.erb

data = '<%= j(render partial: "games/hit_challenges_list")%>';
console.log(data);
$(".hit-list li").append(data);

如果可行或需要其他说明,请告诉我

更新

你的最终 create.js.erb 应该是这样的:

  data = '<%=j render(partial: "games/hit_challenges_list")%>';
  console.log(data);
  $(".hit-list li").append(data);

你应该确保 @hit_challenges@game 被设置在你的控制器中的某个地方,我删除了传递给局部变量的实例变量,因为它是多余的,如果你将局部变量传递给部分,必须是符号。