has_many 的 RESTful 路由:通过关系?
我有 2 个模型 - 用户和活动 - 它们通过 has_many 相关:通过使用 UserActivity 模型。用户可以“想要”或“完成”某项活动,这会创建 UserActivity 记录并设置适当的布尔值。
在创建路由和控制器操作时,您建议如何处理这些操作?像activity/:id/want 和activity/:id/done 这样的东西是否最有意义,因此在活动资源下有2 个成员路由?或者只使用 user_activity 控制器中的更新/创建操作,发布到 /user_activity 进行创建,然后放入 /user_activity/:id 进行更新,会更有意义吗?
I have 2 models - User and Activity - which are related by a has_many :through using the UserActivity model. A User can either "want" or "done" an activity, which creates a UserActivity record and sets the appropriate boolean.
What would you recommend for handling these actions when creating routes and controller actions? Would something like activity/:id/want, and activity/:id/done make the most sense, and thus have 2 member routes under the activity resource? Or would it make more sense to just use the update/create actions in the user_activity controller, with posting to /user_activity for a create, and putting to /user_activity/:id to update?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会采用后一种方法,即允许 POST/PUT 访问“user_activity”。在 REST 世界中,这被视为一种新资源,即使它只是形成“用户”和“活动”资源之间的关系。
我想到的一个想法是将“想要”或“完成”活动类型也分离为新资源(例如“状态”)。这个想法很干净,即使没有它,但如果有机会你必须将列表扩展到“想要”或“完成”之上的东西(例如“有一天/也许”),它可能会更容易将其定义为新资源,而不是现在而不是以后。
因此,您将拥有:
/user
和/user/id
/activity
和/activity/id< /code>
/status
和/status/id
/user-activity
和/user-activity/id
根据您的 URI 设计,您可以在可访问的 URI 中工作,这将允许您获取处于特定状态的用户的所有活动,例如:
/ user-activity/user/{userId}/status/{statusId}
请注意:我无法就 Ruby-on-Rails 的具体细节提供建议(因为我来自 PHP 世界),但我认为(REST)原则应该非常相似。
I would go with the latter approach, i.e. by allowing POST/PUT access to "user_activity". In the REST world this is considered as a new resource even though it just forms a relationship between "user" and "activity" resources.
One thought which comes to mind is to separate "want" or "done" activity types as a new resource as well(e.g. "status"). The idea is clean as it is even without it, but if there is a chance that you will have to extend the list to something on top of "want" or "done" (e.g. "someday/maybe"), it may be easier to define it as a new resource rather now than later.
So you would have:
/user
and/user/id
/activity
and/activity/id
/status
and/status/id
/user-activity
and/user-activity/id
Depending on your URI design you can then work in accessable URIs which would allow you to get all activities for a user which are in a specific state, e.g.:
/user-activity/user/{userId}/status/{statusId}
Please note: I cannot advise on Ruby-on-Rails specifics (as I'm from the PHP world), but I think that the (REST) principles should be very similar.