我在这里有一个相当简单的设置: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强制转换,一切正常,直到我更新Doc
记录,因为重新排序不会在更新时保存。我得出的结论是,因为我的可排序字段在关联表上(即publications
),但由于应用程序的工作方式,它必须是。
我一直在这里做一些研究并发现this问题答案很接近,但因为我有一个Coffeescript行动,首先保存记录它不起作用。
任何帮助都很棒,我真的被卡住了。
答案 0 :(得分:0)
因为我挣扎了很长时间,所以我在这里提出了我的愚蠢简单的解决方案。希望它可以帮助别人。
就像在保存更改之前删除update
上的旧连接表记录一样简单,即:
<强> docs_controller.rb 强>
def update
@doc = Doc.find(params[:id])
@doc.publications.destroy_all
respond_to do |format|
if @doc.update_attributes(params[:doc])
format.html { redirect_to share_url(@doc) }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
动臂。