开发者

RESTful routes for has_many :through relationships?

开发者 https://www.devze.com 2023-01-15 01:10 出处:网络
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

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 ac开发者_如何学运维tivity/: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?


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 resource: /user and /user/id
  • activity resource: /activity and /activity/id
  • status resource: /status and /status/id
  • resource which forms the relationship between user, activity and resource: /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.

0

精彩评论

暂无评论...
验证码 换一张
取 消