Is it possible to use both invested and small resources in rails? How to write a controller / view?

I have resources for which it makes sense to consider them as embedded in other resources, or separately. That is, I expect to use all urls like these:

/account/4/transfers # all transfers which belong to an account /user/2/transfers # all transfers input by specific user /project/1/transfers # all transfers relevant to a project /transfers # all transfers 

my concern is how I can write TransfersController actions (like index) since this will double the logic found in parent models - is there a better way than doing something like

 TransfersController ... def index if !params[account_id].nil? @account = Account.find(params[account_id]) @transfers = @account.transfers elsif !params[user_id].nil? @user = User.find(params[user_id]) if @user.accesible_by?(current_user) @transfers = @user.transfers end elsif !params[projects_id].nil? ..... 

and the same thing applies to submissions - although they will all list transmissions, they will have different headers, navigation, etc. for user, account, project, ...

I hope you see a sample from this example. I think there must be some ugly solution for this. Basically, I would like to separate the logic that selects the displayed translations and other things, such as the contextual parts of the review.

+4
source share
1 answer

I have an open question. In my question, I outlined 2 methods that I came up with. I am currently using the second one and it works very well.

Nested Resource Routing in Rails 3

The route I use is a little different because I use usernames instead of identifiers, and I want them first. You would stick with something like:

 namespace :projects, :path => 'projects/:project_id' do resources :transfers #=> controllers/projects/transfers_controller.rb end # app/controllers/projects/transfers_controller.rb module Projects class TransfersController < ApplicationController # actions that expect a :project_id param end end # app/controllers/transfers_controller.rb class TransfersController < ApplicationController # your typical actions without any project handling end 

The reason I use the namespace instead of calling resources is because Rails allows me to use a separate controller with separate views to handle the same model, instead of inserting all the unpleasant conditional logic into my actions with the controller.

+3
source

Source: https://habr.com/ru/post/1340899/


All Articles