2010-03-08 93 views
2

我希望能够拖拽和拖拽嵌套在Category模型下的App模型。在Rails中排序深层嵌套的属性

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,因为应用程序是类的属性。

我尝试使用

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

但是,我没有传入类别ID,所以它不知道它是哪一类。

这在我看来是

%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") 

任何帮助表示赞赏。

回答

1

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

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

当我移动应用,位置被简单地调用

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

然后,我在模型中相应地对它们进行排序更新。原来没有必要传入类别的ID,只需更新所有应用程序。但是,恐怕它可能会减慢一点,所以如果有人有更好的解决方案,我全都是耳朵。

谢谢