Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - root model or application model

I was just looking around rails and noticed there is an app controller but no app model.

Is there no root model in rails ? if not where do you put a piece of code that needs to be in every model.

Thanks, Alex

like image 476
Alex Avatar asked Jul 25 '10 14:07

Alex


People also ask

What is a model in a Rails application?

A Rails Model is a Ruby class that can add database records (think of whole rows in an Excel table), find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD--Create, Remove, Update, Destroy.

What is the root of a Rails project?

root is an instance of Pathname where RAILS_ROOT is a string.

Does every model need a controller rails?

Do I need a controller for each model? No, not necessarily. However, having one controller per RESTful resource is a convention for a reason, and you should carefully analyze why that convention isn't meeting your needs before doing something completely different.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

Nothing says your controllers have to subclass ApplicationController but it generally is the standard because the vast majority of rails applications make use of the layout capabilities (which can vary on each controller), so instead of forcing the rare ones without layouts from turning the layout off (layout nil or layout false) for each controller, they make an 'abstract' one that you can turn controller features on and off easily for your whole application.

Now for models, you could create an ApplicationModel for all of your models to subclass, but there are two things to think about:

  1. ActiveRecord normally detects when you subclass an already subclassed ActiveRecord::Base and uses this to turn STI (single table inheritance) on.
  2. ApplicationModel will be an actual model that is expected to have a table in your database. This can lead to problems down the line.

To fix these two problems, you have to set abstract_class to true for ActiveRecord to properly function.

class ApplicationModel < ActiveRecord::Base
  self.abstract_class = true
end

In contrast to an abstract ActionController, abstract_class must set to true which means the developer must know they cannot remove this line from ApplicationModel. With ApplicationController you can do pretty much whatever you want to it.

like image 198
Samuel Avatar answered Oct 26 '22 23:10

Samuel