Rails - 更新属性而不删除旧项

时间:2014-12-17 23:12:37

标签: ruby-on-rails ruby-on-rails-4

有谁知道,有RoR方法更新模型的属性而不删除以前的项目吗?

例如,用户拥有很多地点和组织。 params = {location_ids:[1,2,3],organization_ids:[1,2,3]}

user = User.first
user.location_ids --> [3,4,5]
user.organization_ids --> [3,4,5]
user.update(params) --> in this case user will have location_ids as [1,2,3], and organization_ids as [1,2,3]

user.<some_method>(params) --> user has location_ids as [1,2,3,4,5] and organization_ids as [1,2,3,4,5]

或许,你能提出一些像更新这样的特殊方法吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

params[:location_ids] = (user.location_ids + params[:location_ids]).uniq
params[:organization_ids] = (user.organization_ids + params[:organization_ids]).uniq
user.update_attributes(params)

.uniq将确保没有重复项。