Learn Ruby on Rails - Naming Convention for Rails MVC structure
Bài đăng này đã không được cập nhật trong 3 năm
In this post I'll try to explain the Rails MVC Structure and Naming convention with an example. If you have no idea about MVC you should watch this video before continue:
So, lets start:
Suppose, we want to create a table for the user that has three columns (name, age, email). We can name the table "user". But according to the Naming Convention, the table name should be in plural form. So we have to named the table "users". Now, the table looks like:
We created a table "users". Now we want to create a Model for this table in the models folder. In the model, we can write relations, logic or constraints associate with the table "users". So the model name should be the same name as the table but in Singular form. So we'll name the model "user.rb" and Rails will automatically understand that the "user.rb" is the model for the table "users".Now, the situation is like this:
Now, we want to create a controller for the Model "user.rb". And the name of the controller should be in plural form and it should be end with "_controller". So the name of the controller for our case, will be "users_controller.rb" And by the name, Rails will understand that "users_controller.rb" is the controller for "user.rb". Now, the situation is like this:
And the name of the View part depends on the methods of the controller. If the controller "users_controller.rb" has two viewable methods (index, show) then there will be two view files under views/users/ directory. The name of the files will be "index.html.erb" and "show.html.erb". And again, by naming convention, Rails knows that it has to render "index.html.erb" when the "index" method of "users_controller.rb" will be called. So, now the total situation is like this:
For another example, if we want to create a "category" table, then the name should be like this:
- table name: categories (plural form of category is categories)
- model name: category.rb (singular form)
- controller name: categories_controller.rb (plural form)
In the next post, I'll try to explain how to pass instance variables and call methods among Model, Controller and Views.
All rights reserved