【问题标题】:Updating extra column in a has_many, :through table with Coffeescript使用 Coffeescript 更新 has_many, :through 表中的额外列
【发布时间】: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


    【解决方案1】:

    因为我为此苦苦挣扎了很长时间,所以我将我愚蠢的简单解决方案放在这里。希望它可以帮助其他人。

    就像在保存更改之前删除 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
    

    轰隆隆。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      相关资源
      最近更新 更多