I used "rails generate scaffold Post title:string body:text" to create a model and related controller etc. I was surprised to find the model and controller files empty. I thought the model file would contain instance variables to store each post's title and body attributes. Can someone explain to me why the Post model file running generate scaffold is empty even though the data items do show up in the database. When I bring up the webpage and go to the .../posts url I can see the json listing of the ones I created. Thanks.
-
The model will be empty, but the controller should not be empty.hashrocket– hashrocket2017-05-17 02:09:56 +00:00Commented May 17, 2017 at 2:09
-
You're right the controller is not empty. I misspoke on that part.user3064141– user30641412017-05-17 03:04:32 +00:00Commented May 17, 2017 at 3:04
Add a comment
|
1 Answer
Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting.
Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”.
The reason your model is empty is because Rails doesn't know what you want your models to do. It knows you want basic CRUD functionality, so it fills in your controllers accordingly.
3 Comments
user3064141
I guess that is why I'm a little confused. Since Ruby is using the model class to store the data when the controller performs CRUD operations on the database to retrieve the "Post" datatypes, I would have thought the resulting Post model class would contain at least a place holder string for the title and body attributes instead of being empty. I guess that is why I'm a little confused. Thanks for the reply.
rmcsharry
This question and answer might help your understanding of why the model file is empty: stackoverflow.com/questions/34701667/…
user3064141
thanks for the replies. they led me to look into it further and I was able to clear things up for myself. I forgot that the root foundation of ruby on rails is convention over configuration, and based on that the parent class ActiveRecord::Base uses the name of your model "Post" and assumes you want it to perform a query against a table of the same name but pural "posts". The following links helped me remind myself of that: api.rubyonrails.org/files/activerecord/README_rdoc.html edgeapi.rubyonrails.org/classes/ActiveRecord/Base.html