【发布时间】:2015-02-17 07:55:28
【问题描述】:
我有以下型号
class User < ActiveRecord::Base
has_many :user_wishes
has_many :wishes, through: :user_wishes
end
class UserWish < ActiveRecord::Base
belongs_to :user
belongs_to :wish
end
class Wish < ActiveRecord::Base
has_many :user_wishes
has_many :users, through: :user_wishes
end
现在我有了以下界面,用户可以在其中选择/取消选择愿望。
一旦用户完成选择/取消选择,他就会提交表单。现在我在后端所做的就是为给定的user_id 和wish_id 创建或销毁user_wishes 记录。
现在有两种方法可以实现我能想到的这个解决方案。
1。通过计算现有愿望和新愿望之间的差异
假设用户已经有 N 个愿望,现在他用 M 个愿望提出一个新请求。我将删除 (N - M) 的差异并添加 (M - N) 的差异。这种方法似乎非常低效,因为我总是必须通过网络发送 (N ∩ M)。
端点: /user_wishes
类型: POST ?但它也会删除记录
参数: {wish_id: [1,2 ..], user_id: 10}
2。通过只发送改变的那些
我将在前端有逻辑,它给我一个新添加/删除的愿望列表。
端点: /user_wishes
类型: POST ?但它也会删除记录
参数: {added_wish_ids: [1,2 ..], removed_wish_ids: [12, 16], user_id: 10}
我现在正在使用这种方法,但这对我来说似乎不是 RESTful !
我想知道解决此问题的最佳方法是什么。这应该去什么端点,请求类型应该是什么?
【问题讨论】:
标签: ruby-on-rails rest ruby-on-rails-4 has-many-through