简体   繁体   English

Ruby on Rails: 新的 controller 照片?

[英]Ruby on Rails: New controller for photos?

I have a one-to-many relationship between my Profile class and Photos class.我的个人资料 class 和照片 class 之间存在一对多的关系。 Profile holds the user's information and photos holds the user's pictures. Profile 保存了用户的信息,photos 保存了用户的图片。 Currently, the "Upload photo" link shows at the bottom of the profile view.目前,“上传照片”链接显示在个人资料视图的底部。 I want to have the link show up on a separate view instead of cramming everything on the same form.我想让链接显示在单独的视图上,而不是将所有内容都塞在同一个表单上。 Should I just create a new view called profile_photo.html.erb to show this link or should I create a new controller and model that associates with the photos?我应该只创建一个名为 profile_photo.html.erb 的新视图来显示此链接,还是应该创建一个与照片关联的新 controller 和 model? What's the recommended practice?推荐的做法是什么?

The "Photos" class should be called "Photo", as Rails uses singular names for models. “照片” class 应该被称为“照片”,因为 Rails 对模型使用单数名称。

Yes you should create a new controller for creating photos because it's another resource.是的,您应该创建一个新的 controller 来创建照片,因为它是另一种资源。 You'll probably want to edit the photos eventually, adding descriptions and so on.您可能最终想要编辑照片,添加描述等等。

I agree with Radar, you'll want to create a PhotosController.我同意 Radar,你会想要创建一个 PhotosController。 When you do that then you can take it a step further and define the has_many relationship in the routes.rb file as well.当您这样做时,您可以更进一步,并在 routes.rb 文件中定义 has_many 关系。 Like so:像这样:

   map.resources :photos
   map.resources :profiles, :has_many => :photos

This will generate urls like profile_photos_path , new_profile_photo_path , etc... run the rake routes command to see what it gives you.这将生成诸如profile_photos_pathnew_profile_photo_path等 url...运行rake routes命令以查看它为您提供的内容。 This will help to keep you code DRY and easy to read.这将有助于使您的代码保持干燥且易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM