【发布时间】:2015-11-10 16:20:33
【问题描述】:
我有一个呈现两个表单部分的视图:
匹配/new.html.erb:
<%= render 'players/new' %>
<%= render 'matches/form' %>
matches/form 是一个新匹配的形式。在表单上,您可以将现有玩家添加到团队。 Players 集合呈现为复选框的集合。提交表单后,将创建包含选定玩家的团队:
匹配/_form.html.erb:
<%= form_for @match do |f| %>
<%= f.fields_for :team_1 do |team_1_form| %>
<%= team_1_form.label "Team 1" %><br>
<%= team_1_form.collection_check_boxes :player_ids, Player.all, :id, :name, include_hidden: false %>
<% end %>
<br>
<%= f.fields_for :team_2 do |team_2_form| %>
<%= team_2_form.label "Team 2" %><br>
<%= team_2_form.collection_check_boxes :player_ids, Player.all, :id, :name, include_hidden: false %>
<% end %>
<br>
<%= f.submit "Start Match" %>
<% end %>
在players/new中你可以创建新的Players:
玩家/_new.html.erb:
<%= form_for @player, remote: true do |f| %>
<%= f.text_field :name %>
<%= f.submit 'Create Player' %>
<% end %>
所以我的想法是,我希望能够通过 AJAX 创建一个播放器(顺便说一下,表单确实成功了),并将该播放器的复选框添加到视图中的播放器复选框集合中,而无需页面刷新。
我尝试了一些不同的东西(您会在 create.js.erb 文件中看到一些被注释掉的东西)。我已经坚持了好几天了,我已经用谷歌搜索了它。请帮忙!
Github 仓库:https://github.com/Yorkshireman/foosball
控制器:
class PlayersController < ApplicationController
def create
@player = Player.create(name: params[:player][:name], league: current_league)
@match = Match.new
current_league.players << @player
respond_to do |format|
format.js {}
end
end
end
class MatchesController < ApplicationController
def new
@player = Player.new
@players = Player.all
@match = Match.new
end
def create
@match = Match.new(league: current_league)
if team_1_player_ids && team_2_player_ids
teams = BuildTeams.call team_1_player_ids, team_2_player_ids, current_league
InsertTeamsIntoMatch.call teams, @match
@match.save
render nothing: true
else
flash[:alert] = "Please select players for both teams"
render :new
end
end
private
def team_1_player_ids
params[:match] && params[:match][:team_1] && params[:match][:team_1][:player_ids]
end
def team_2_player_ids
params[:match] && params[:match][:team_2] && params[:match][:team_2][:player_ids]
end
end
views/players/create.js.erb:
// $("<%= escape_javascript(render partial: 'matches') %>");
// $('#new_match_div').html("<%= escape_javascript(render 'matches/new') %>");
$('#new_match').html("<%= escape_javascript(render 'matches/form') %>");
// $('#new_match').replaceWith("<p>Replaced</p>");
【问题讨论】:
-
当你的
create.js.erb只包含$('#new_match').replaceWith("<p>Replaced</p>");时发生了什么? -
ActionView::Template::Error(缺少部分播放器/_matches,应用程序/_matches 与 {:locale=>[:en], :formats=>[:js, :html], :variants =>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}。搜索:* "/home/andrew/projects/foosball/app/views"):
-
我询问了
.replaceWith("<p>Replaced</p>");您正在报告指定的部分。我猜那是给$("<%= escape_javascript(render partial: 'matches') %>");的。你可能想要这个:$('#new_match').html("<%= escape_javascript(render partial: 'matches/form') %>");. -
当使用渲染部分:'matches/form'时,不会出现新的复选框。页面刷新使其出现。
-
在您的
collection_check_boxes方法调用中,players是局部变量吗?您为players分配了什么值?如果您将players替换为Player.all,您可能会得到您期望的结果。
标签: ruby-on-rails ajax