2011-01-08 83 views
-1

我有2个模型,用户和项目。现在,它们通过has_and_belongs_to_many连接(多对多)连接。用户有一个项目列表,这个列表可以通过ajax排序。但我想存储这个订单。我该如何发送此订单并以适当方式存储?如何在Ajax列表中存储项目的顺序?

回答

1

要sorteable列表我jQueryUI的工作 - >http://jqueryui.com/demos/sortable/

以获取列表:

var projects = Array(); 
var j=0; 

$("#sortable li").each(function(i, item){ 
    projects[j] = $("#"+item.id).html();    
    j++; 
}); 

var data = {"list": projects}; 

然后我用Ajax

1

发送数据,你必须考虑项目的顺序在用户列表上作为用户和项目之间的关系的属性。每对用户/项目都有一个属性“订单”,对吧?

因此,信息应该放在中介表(projects_users)中。

但是,因为你不能属性添加到have_and_belongs_to_many链接表,你应该改变它的东西,如:

class User 
    has_many :allocations 
    has_many :projects, :through => :allocations 
end 

class Project 
    has_many :allocations 
    has_many :users, :through => :allocations 
end 

,并在分配表中的迁移应该是这样的:

create_table :allocations do |t| 
    t.integer :project_id 
    t.integer :user_id 
    t.integer :order 
end 

这样,对于给定用户分配给每个项目,您可以指定订单。

我希望这会有所帮助。

+1

该表应该有一个ID权?我认为你创建HABTM表时只使用:id => false。 – RobinBrouwer 2011-01-08 16:21:03

1

你可以做的是循环遍历所有使用Javascript的项目,并使用AJAX将一个ID数组发送到Rails动作(如Manu Mora示例所示)。这些参数会是这个样子:

project_ids: 1,3,5,2,4 
id: 1 

然后在你的控制器动作,你可以做到以下几点:

@user = User.find(params[:id]) 
@user.update_attributes(:project_ids => params[:project_ids].split(",")) 

我不知道如何发送参数的方式,它是一个数组自动,所以我使用split。我不知道使用HABTM时订单是否合适。如果不是,则应使用has_many :through,并在'订单'或'位置'列中使用。我展示给你的方式不会奏效,因为你还需要设置订单栏。

希望它有效。 :)

相关问题