Thillai Narayanan
Thillai Narayanan

Reputation: 4886

Is the following naming convention needed in a rails project?

My project name is clog, so I named my models and controllers like this: Clog::User Clog::Userscontroller.

Is this naming convention mandatory?

Upvotes: 4

Views: 646

Answers (2)

Marek Příhoda
Marek Příhoda

Reputation: 11198

No, in a conventional Rails project, that's not necessary. Just name your models and controllers the usual way, like eg User or UsersController.

The other thing is that, when your project grows in size, you may need to organize your models into submodules. One approach to do so is extending your models with app concerns, as show eg here or here.

As for organizing controllers, one approach is to create a module in the lib directory, which you then include in your ApplicationController, like so:

In lib/authentication.rb:

module Authentication
  def self.included(base)
    base.send :before_filter, :login_required
    base.send :helper_method, :current_user, :logged_in?
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token]) if cookies[:remember_token].present?
  end

  #...
end

In app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include Authentication

  #...
end

For this to work, you need to add

config.autoload_paths << "#{config.root}/lib"

to your config/application.rb file

However, if you plan to build your Rails project as a Rails Engine, you may want to follow some naming convention. A good example of a Rails Engine is forem.

Upvotes: 2

Jaryl
Jaryl

Reputation: 2601

Yes, following the naming convention helps a great deal because not only does rails use it to generate other names, but other gems as well.

Specific to your question, you may be asking if you need to name the controller as UserController given that your model is called User. That is not necessary at all, and you may call it anything else if it better fits your purpose.

In this case, you will probably want to create a few controllers like so:

My::AccountController # for e.g.. /my/account
Admin::UsersController # for e.g. /admin/users/1

For a user, you refer to your own user record, as 'your account' so this makes more sense. However, the administrator's perspective would be to manage user records. You may also name a controller one thing and serve it under a different route. In your routes file, you may do this:

namespace :admin do
    resources :users, :path => "user-accounts"
end

To reiterate, your model name need not match up to the controller name. They are only named similarly by association: UserController is understood to handle User records.

Upvotes: 0

Related Questions