多对多关联和 REST?
新手问题,已警告您!
我正在尝试实现一个具有多对多关联的示例 Rails 应用程序,人们拥有电影,并且我正在尝试弄清楚如何准确地实现它的 UI。我的理解是,REST 要求一切都成为资源,因此在本例中是“用户”(人)、“电影”和“拥有”(联合表)(哦,双关语)。
现在有趣的部分是用户体验。假设我有一个用户仪表板,其中列出了您的所有电影。
假设用户想要添加他拥有的电影。在 REST 中如何做到这一点?可以将自定义操作添加到用户控制器中,这很简单,但重点不在于超出基本的 7 个 REST 操作,对吗?因此,我必须首先对电影进行“新”操作,然后对财产进行“新”操作,这是两个操作。我如何将它们合二为一?
基本上,我觉得我不太明白如何在涉及多个模型时维护 REST,并且希望得到提示。
谢谢!
Newbie question, you've been warned!
I'm trying to implement a sample Rails app with a many-to-many association, people owning movies, and I'm trying to figure out how exactly to implement the UI for it. It's my understanding that REST requires everything to be a resource, so in this case "User" (person), "Movie" and "Possession" (the joint table) (oh, the puns).
Now the interesting part, the UX. Let's say I have a user dashboard where all of your movies are listed.
Let's say the user wants to add a movie that he owns. How do you do this in REST? It's trivial with a custom action that one could add to the User controller, but the point is not to go beyond the basic 7 REST actions, right? Therefore I'd have to first do a "new" on a movie and then do a "new" on a possession, which are two operations. How do I collapse them into one?
Basically I feel I'm not quite understanding how to maintain REST as soon as multiple models are involved and would appreciate a tip.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
令人高兴的是,Rails 对于这种常见场景有一些魔力。假设这样的模型:
您的观点:
基本上,此表单将
POST
到MoviesController#create
并将current_user.id
作为传递>user_id
参数(默认)MoviesController#create
将知道与其创建的Movie
关联。查看FormBuilder#form_for 的文档
了解更多信息。顺便说一下,您也可以以相反的方式执行此操作:
视图:
在这种情况下,表单将提交给
UsersController#update
,其参数将如下所示:...和控制器将知道创建
Movie
对象。有关更多信息,请查看FormHelper#fields_for 的文档
。Happily, Rails has some magic just for this common scenario. Assuming a model like this:
Your view:
Basically this form will
POST
toMoviesController#create
and will pass alongcurrent_user.id
as auser_id
parameter that (the default)MoviesController#create
will know to associate with theMovie
it creates. Take a look at the documentation forFormBuilder#form_for
for more information.You could also do this the other way around, by the way:
And the view:
In this case the form will submit to
UsersController#update
and its parameters will look like this:...and the controller will know to create the
Movie
object. For more information check the documentation forFormHelper#fields_for
.