ruby - Rails best practice: Handling multiple relations in a single controller -


My app has a photo model, these photos may be related to some other classes, such as topics, users, tags. I want to be able to query all the photos based on different related IDs. I have established nested resources:

  resources: topics are resources: photos, only: ['index'] end ... resources: users use resources: photos, only: ['Index'] end  

I am thinking that what is the best practice to handle it in the controller is my initial reaction is to write one / the other block, but this handkerchief is. # Query User ID is based on ELSF! Parameters [: topic_id] .nil? Based on topic ID, etc. # Query

I also discussed setting routing functions and routing for those users, such as user_photos # photos, topic_photos # photos.

Or settings some new controllers: UserPhotosController, Theme Controller

None of these seems right and I am thinking that someone has some insights or if doing so There is no general design pattern.

This is a Rail 4 project, BTW.

First things first, in Rail 4, you can use: Concern: Image Resource: Photo, Only: ['Index'] End Resource: Topics, Concerns: imageable Resources: Users, Concerns :: imageable

Option A : Move any other method, which is just image-able, i.e. users, tags, topics etc. In your PhotosController:

  rescue_profile activivercord :: recordNotFound, with => with : Render_404 DEF Index Answer with Photo End Personal DF Photo @ photos || = Created? Imageable.photos: Use the find_by_id instead of searching by using the Find_by_id instead to search for an image based on ID and cache in Photo.all end # parameter to ensure that ActiveRecord :: RecordNotFound # passes an invalid ID , The render_404 method can be handled with defable @imageable = = if id = param [: user_id] User.find (id) elsif id = params [: topic_id] Topic.find (id) end end end Def render_404 response_to do format | Format.html {Render Template: 'Errors / No_Found', Layout: 'Layout / Application', Status: 404} format.all {None Render: true, Status: 404} End End  

Option B : Change your routes instead:

  Resource: Photos, only: ['index'] Processing: Subject Resources: User Ends < / Code> 

and then TopicsController , UsersController , then change it accordingly and then you UserPhotosController , , etc.


Comments