0

我在这里有一个相当简单的设置:一个Doc模型、一个Publication模型和一个Article模型。

文档.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

出版物.rb

class Publication < ActiveRecord::Base
  attr_accessible :doc_id, :article_id, :position
  belongs_to :doc
  belongs_to :article
  acts_as_list
end

文章.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

我遵循了 Rails cast 的这个可排序列表,在我更新记录之前一切正常,Doc因为更新时不会保存重新排序。我得出的结论是,这是因为我的可排序字段位于关联表(即publications)上,但由于应用程序的工作方式,它必须如此。

我一直在这里做一些研究,发现这个问题的答案很接近,但是因为我有一个 Coffeescript 操作首先保存了记录,所以它不起作用。

任何帮助都会非常好,我真的被困住了。

4

1 回答 1

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

繁荣。

于 2013-01-29T02:05:10.430 回答