0

ここではかなり単純な設定をしています: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

出版.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の sort メソッドです:

def sort
  Article.all.each_with_index do |id, index|
    Publication.update_all({position: index + 1}, {id: id})
  end
render nothing: true
end

私はこの並べ替え可能なリスト Rails のキャストに従いましたが、更新時に並べ替えが保存されないため、レコードを更新するまではすべて正常に機能します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 に答える