使用嵌套资源组织控制器的正确方法(rails)
我希望这个问题不太主观,但就这样吧。
为了简单起见,我有一个包含许多嵌套资源的用户模型。例如,一个@user有许多@books、@cars、@friends。
在用户的“显示”视图中,我向用户展示了一个仪表板,其中显示了他们所有东西(书籍、汽车和朋友)的小部件。
我现在的问题是 UsersController 必须执行与书籍、汽车和朋友有关的任何/所有逻辑。将书籍等的逻辑放在 UsersController 中感觉是错误的。
I'm hoping this question isn't too subjective, but here goes.
For simplicity sake, I've got a User model with many nested resources. For instance, a @user has many @books, @cars, @friends.
In the user's "show" view, I present the user with a dashboard, that shows widgets for all of their things (books, cars, and friends).
My issue now is that the UsersController has to do any/all logic pertaining to books, cars, and friends. And putting logic for Books, etc in the UsersController just feels wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Rails 中,您可以在路线中使用嵌套资源,就像这样,
这会给您类似的内容
,它会命中您的图书控制器的索引,只需检查图书控制器内的 user_id 可用性,并获取附加到当前用户的所有图书(如果存在)。
通过这种方式使用控制器和路由,您可以轻松地将逻辑扩展到更适合的控制器,并将其排除在用户控制器之外。
查看下面的文档以获取更多信息,例如新嵌套路径的巧妙助手。
http://guides.rubyonrails.org/routing.html#nested-resources
In rails you can use nested resources in your routes like so
That would give you something like
Which would hit the index of your books controller, simply check for user_id availability inside your books controller and fetch all books attached to the current user if its there.
Using your controllers and routing this way you can easily spread your logic around to better suited controllers and keep it out of your users controller.
Check out the docs below for more information like snazy helpers for your new nested paths.
http://guides.rubyonrails.org/routing.html#nested-resources
发表评论后不久,我在 Rails 指南上发现了 :before_filter 。使用此功能,您可以根据是否找到嵌套资源以及相关模板来调用操作。这就是我所做的,并且对我来说效果很好!
以及它调用的方法的示例
Shortly after commenting I found the :before_filter on the Rails guide. Using this, you can call actions based on whether the nested resource is found, and the related template. This is what I did, and works well for me!
and an example of a method it calls