【发布时间】:2013-01-05 04:26:14
【问题描述】:
我在这里有一个相当简单的设置:Doc 模型、Publication 模型和 Article 模型。
doc.rb
class Doc < ActiveRecord::Base
attr_accessible :article_ids,:created_at, :updated_at, :title
has_many :publications, dependent: :destroy
has_many :articles, :through => :publications, :order => 'publications.position'
accepts_nested_attributes_for :articles, allow_destroy: false
accepts_nested_attributes_for :publications, allow_destroy: true
end
publication.rb
class Publication < ActiveRecord::Base
attr_accessible :doc_id, :article_id, :position
belongs_to :doc
belongs_to :article
acts_as_list
end
article.rb
class Article < ActiveRecord::Base
attr_accessible :body, :issue, :name, :page, :image, :article_print, :video, :id
has_many :publications
has_many :docs, :through => :publications
end
Doc 表单允许用户选择和订购许多文章:
...
<% @articles.each do |article| %>
<span class="handle">[drag]</span>
<%= check_box_tag("doc[article_ids][]", article.id, @doc.articles.include?(article), :class => "article_chooser" ) %>
<a id="<%= article.id %>" class="name"><%= article.name %></a>
<% end %>
...
这个 Coffeescript 在拖动时保存订单:
jQuery ->
$('#sort_articles').sortable(
axis: 'y'
handle: '.handle'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
);
这是 docs_controller.rb 中的排序方法:
def sort
Article.all.each_with_index do |id, index|
Publication.update_all({position: index + 1}, {id: id})
end
render nothing: true
end
我已经关注了this 可排序列表 Rails cast 并且在我更新Doc 记录之前一切正常,因为更新时不会保存重新排序。我得出的结论是,这是因为我的可排序字段在关联表上(即publications),但由于应用程序的工作方式,它必须如此。
我一直在这里做一些研究,发现this 问题的答案很接近,但是因为我有一个 Coffeescript 操作首先保存记录,所以它不起作用。
任何帮助都会很好,我真的被困住了。
【问题讨论】:
标签: ruby-on-rails-3 coffeescript jquery-ui-sortable has-many-through