【问题标题】:Sorting deeply nested attributes in Rails在 Rails 中对深度嵌套的属性进行排序
【发布时间】:2010-03-08 05:01:55
【问题描述】:

我希望能够拖放嵌套在 Category 模型下的 App 模型。

http://railscasts.com/episodes/196-nested-model-form-part-1

这是我尝试关注的 Railscast。

#Category controller
def move
  params[:apps].each_with_index do |id, index|
    Category.last.apps.update(['position=?', index+1], ['id=?', Category.last.id])
  end
  render :nothing => true
end

我可以用类似的东西对类别进行排序,但是由于我正在更新属性,所以我遇到了麻烦。这就是我对类别列表进行排序的方式。

def sort
  params[:categories].each_with_index do |id, index|
    Category.update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end

经过进一步检查,我需要能够同时更新所有应用程序,除了我不能只执行 App.update_all,因为 App 是类别的属性。

我尝试过使用

@category = Category.find(params[:id])
@app = @category.apps.all

但是,我没有传入Category id,所以它不知道它是哪个Category。

在我看来是这样的

%ul#apps
  - for app in @category.apps
    - content_tag_for :li, app do
      %span.handle
        [drag]
    = h app.title

= sortable_element("apps", :url => move_categories_path, :handle => "handle")

感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails nested-attributes


    【解决方案1】:

    原来这只是按位置对记录进行排序的问题。我在控制器中对类别进行排序。所以对于嵌套的属性模型,我在模型中进行了排序:

    has_many :apps, :dependent => :delete_all, :order => "position"
    

    当我移动应用程序时,只需调用即可更新位置

    App.update_all(['position=?', index+1], ['id=?', id])
    

    然后我在模型中对它们进行相应的排序。原来没有必要传递类别的 id,只需更新所有应用程序。但是,我担心它可能会慢一点,所以如果有人有更好的解决方案,我会全力以赴。

    谢谢

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多