Mel Mel - 3 months ago 10
Ruby Question

Rails 4 - routing using concerns

I am trying to figure out how to use concerns in my routes file.

I have models called User, Project and Eoi.

The associations are:

User

has_many :eois


Project

has_many :eois


Eoi

belongs_to :user
belongs_to :project


I am trying to make a system to show eois that have been submitted on a project, so that they are visible only to the user that made the project.

Separately, I want to show every user all of the eois that user made (regardless of which project they are made on).

I think I want nested routes for the first scenario and then I also want eoi routes that are not nested for the second scenario.

In my routes.rb

I have:

resources :projects do
# concerns: :eois,
member do
resources :eois
end


I also want to have:

resources :eois


How can I make this work? I can't get the hang of the examples in this http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Concerns.html

I don't understand whether commendable in the example is a model or if its something I need to write to be able to have routes in two places in the routes.rb file.

My next attempt is to try to copy the gist of the example in the above link, I have

resources :eois#, only: [:index]
concern :eoiable do
resources :eois
end

resources :projects do
concerns :eoiable
end


I'm not sure if i need to make a definition somewhere to get this working.

Answer

Route concerns are needed only when you want to DRY your routes. So far you have only one route duplication (eoi) so... using a concern is an overkill here.

What you actually want to do is to have 2 eoi controllers, one will be responsible for providing all eois, second only for that ones which are inside the project.

For better readability I'd namespace them – put one eois_controller.rb inside projects folder and named it as Projects::EoisController, second one - as a top-level controller, named EoisController. Routes would look like this:

resources :eois # will map to EoisController
resources :projects do
  scope module: :projects do
    resouces :eois # will map to Projects::EoisController
  end
end

And, of course, you might want to DRY these 2 controllers afterwards.