【问题标题】:Using ranked model with rails 4使用带有 rails 4 的排名模型
【发布时间】:2013-12-04 05:12:19
【问题描述】:

我一直在使用ranked model 并关注此sortable tables tutorial

我为此烦恼不已,任何人都可以提供帮助的任何事情都很棒!

我有Decks,其中有很多Cards。在套牌编辑页面上,我正在尝试对其自己的套牌进行排序。

card.rb

belongs_to :deck
include RankedModel
ranks :row_order, :with_same => :deck_id

routes.rb

resources :decks do 
  post :sort, on: :collection
  resources :cards
end

decks_controller.rb

def sort
  @deck = Deck.find(params[:id])
  @deck.update_attributes(deck_params)
  @deck.save
  render nothing: true
end

def deck_params
  params.require(:deck).permit(:name, :id, :cards_attributes => [:id, :question, :answer, :deck_id, :_destroy, :row_order, :row_order_position])
end

jquery

$.ajax({
  type: 'POST',
  url: $(this).data('update_url'),
  dataType: 'json',
  data: { id: deck_id, deck: { cards_attributes: { row_order_position: position } }}

这一切都在 Rails 4 上。 我认为问题在于我如何发布数据。

我已经检查了卡片本身的row_order,它正在设置中。我似乎无法理解如何使用嵌套的cards_attributes 通过 ajax 传递信息。

我也不确定为什么教程在 ajax 帖子中显示 row_order_position: position,而我认为它只是 row_order: position

【问题讨论】:

    标签: jquery ruby-on-rails ajax jquery-ui ruby-on-rails-4


    【解决方案1】:

    这里有几件事(我打算写评论,但作为答案会更容易阅读):


    它是否如您所愿?

    我查看了您的代码,您似乎只是想更改卡片组的 position,而在您的 ajax 中没有回调

    这是您想要的工作方式吗?就个人而言,我会创建一个名为DeckPosition 的单独模型,您可以像这样使用它:

    #app/models/deck_position.rb
    Class DeckPosition < ActiveRecord::Base
        belongs_to :deck, :class_name => 'Deck'
        belongs_to :card, :class_name => 'Card'
    end
    
    #app/models/deck.rb
    Class Deck < ActiveRecord::Base
        has_many :card_positions, :class_name => 'DeckPosition'
        has_many :cards, :class_name => 'Card', :through => :card_positions
    
        accepts_nested_attributes_for :cards
    end
    
    #app/models/card.rb
    Class Card < ActiveRecord::Base 
        has_many :deck_positions, :class_name => 'DeckPosition'
        has_many :decks, :class_name => 'Deck', :through => :deck_positions
    end
    

    然后我会在连接模型中包含属性“order”:

    deck_positions table
    id | deck_id | card_id | row_order_position | created_at | updated_at
    

    这可能是完全错误的,但从你的问题来看,这似乎是你可以从中受益的东西


    嵌套属性

    您似乎将嵌套属性传递给您的卡片模型,但您的代码中没有对此的任何引用?我在自己的代码中将适用的代码添加到Deck 模型中;所以也许你想看看那个?


    排序

    我询问您的 Ajax 的原因之一是您正在向服务器发送请求,但似乎没有处理它?这很重要,因为虽然我以前没有使用过排名宝石,但您似乎希望能够对应用程序的一些重要方面进行排序?您希望如何处理它们?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多