Reputation: 1687
I hope you can help me with this.
I have a model User
and two controllers UserController
and AdminController
. Also I have another model called Article
( and a ArticleController
).Also I have some relations between this models.
class User
...
has_many :articles
end
I need my routes would look something like this :
resources :admin do
...
resources :articles do
end
end
resources :users
...
resources :articles do
end
end
So, I need both, common users and the admin, could create, list and delete articles. Since I only have one create, destroy, edit and update function for ArticleController
how can I achieve what I want? . The deal is that after a common user creates an article, it needs to sent to a particular view in User
views, and if the Admin
creates an article, it needs to redirects to a particular view in Admin
views, all this would be done by placing some IF
clauses in the create
function, depending on the previous url. Is that correct, is it a good practice. Maybe should I create all these views in the Article folder?. Other thing I came up with is creating different create
functions in ArticleController
and the same for edit, new and update functions.
Maybe the question is kind of silly, but I am kind of newbie in Ruby.
Thanks in advance
Upvotes: 0
Views: 318
Reputation: 76774
Namespace
To expand on David Underwood
's answer, you're probably looking to use namespacing
in your app
This works by leading Rails to look for a module
prepending the controllers in a particular namespace
, like this:
#config/routes.rb
namespace :admin do
resources :articles, only: :show #-> domain.com/admin/articles/15
end
This leads Rails to look for the articles
controller in:
#app/controllers/admin/articles_controller.rb
class Admin::ArticlesController < ApplicationController
end
--
This will allow you to define actions which only occur in the admin
namespace, thus giving you the capacity to create / edit / update the various records you want
I think this is the general answer you need. In regards to sending the user to different views after the controller, you'll be able to use redirect_to
in both controllers
We use namespacing to create admin
areas in our apps
Upvotes: 1
Reputation: 4966
Use two controllers.
In your controllers directory create a sub-folder called admin
and in there create a controller called Admin::ArticlesController
. This allows you to put all admin-related actions in a specific place and all user-related actions in another.
There's more info on namespacing controllers in the Rails Guides here: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
Upvotes: 2