2

我希望能够拖放嵌套在 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")

任何帮助表示赞赏。

4

1 回答 1

1

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

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

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

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

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

谢谢

于 2010-03-08T06:07:03.203 回答