继Railscasts关于可排序列表(http://railscasts.com/episodes/147-sortable-lists-revised?view=asciicast)的剧集之后,我已经掌握了一切,但不是在#show动作显示列表的模型上进行排序,而是一个嵌套模型。Rails 3.2使用嵌套资源的jQuery可排序列表500错误
我的网站是用于管理一个非常复杂的幻想足球联赛。联盟的一个方面是,通用汽车拥有年薪上限,玩家有价值,玩家可以签署多年合同。
无论如何,我正在创建一个草稿名单列表,可以让您添加球员并跟踪您想要尝试和选中的球员。我希望这个列表是可排序的。我使用has_many:through关系进行设置。
这里有三种型号:
class DraftRoster < ActiveRecord::Base
attr_accessible :name, :team_id
belongs_to :team
has_many :roster_spots
has_many :players, through: :roster_spots
...
end
然后:
class RosterSpot < ActiveRecord::Base
attr_accessible :draft_roster_id, :player_id, :position
belongs_to :draft_roster
belongs_to :player
acts_as_list
end
最后(这有此作为其不适用删除这个问题很多更多的代码):
class Player < ActiveRecord::Base
attr_accessible :auction_value, :first_name, :last_name, :nfl_team, :position, :is_drafted, :is_bought_out, :is_extended, :is_franchised, :bye_week, :full_name, :contracts_attributes, :subcontracts_attributes
...
has_many :roster_spots
has_many :draft_rosters, through: :roster_spots
...
end
所以我经历了,我完全按照Railscasts情节。我的#sort操作位于roster_spots_controller.rb文件中(位置属性也在此模型中)。
draft_rosters_controller.rb
def sort
params[:roster_spot].each_with_index do |id, index|
RosterSpot.update_all({ position: index + 1 }, { id: id })
end
render nothing: true
end
和我有必要途径:
resources :roster_spots do
collection { post :sort }
end
的CoffeeScript的:
jQuery ->
$('#draft-roster-players').sortable(
axis: 'y'
handle: '.handle'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
)
的draft_rosters#show动作:
def show
@draft_roster = DraftRoster.find(params[:id])
@team = @draft_roster.team
@players = @draft_roster.players.order("position")
respond_to do |format|
format.html # show.html.erb
format.json { render json: @draft_roster }
end
end
最后,认为:
<ul id="draft-roster-players" data-update-url="<%= sort_roster_spots_url %>">
<% @players.each do |player| %>
<%= content_tag_for :li, player do %>
<span class="handle">[drag]</span>
<%= link_to h(player.full_name), player %>
<% end %>
<% end %>
</ul>
一切都拖着如预期下降,但是当我把一个球员到一个新的点就行了,在Chrome的JavaScript控制台,我不断收到此错误:
POST http://localhost:3000/roster_spots/sort 500 (Internal Server Error)
send
x.extend.ajax
x.(anonymous function)
$.sortable.update
$.Widget._trigger
$.widget._trigger
(anonymous function)
(anonymous function)
$.widget._clear
(anonymous function)
$.widget._mouseStop
(anonymous function)
$.widget._mouseUp
(anonymous function)
_mouseUpDelegate
x.event.dispatch
v.handle
我不明白。我能想到的唯一的事情就是它与嵌套资源有关,但我不明白为什么这个问题是必要的。关于Railscasts插曲的一些评论提到嵌套资源存在一些问题,但他们中没有一个提供了他们用于使其工作的解决方案,而且他们来自多年前。
有没有人通过jQuery在Rails 3.2应用程序中完成可排序列表?有什么诀窍让它工作?我试过将一些变量传递给标签上的data-update-url属性,但没有任何工作。
任何帮助,将不胜感激!
更新愚蠢的是,我从来没有检查过Rails控制台输出...我得到这个错误:
NoMethodError (undefined method `each_with_index' for nil:NilClass):
app/controllers/roster_spots_controller.rb:89:in `sort'
我不能回答我自己的问题8个小时,所以我不得不回来,并重新将此作为答案,但我想通了: –