1

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.

2
  • The model will be empty, but the controller should not be empty. Commented May 17, 2017 at 2:09
  • You're right the controller is not empty. I misspoke on that part. Commented May 17, 2017 at 3:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
This question and answer might help your understanding of why the model file is empty: stackoverflow.com/questions/34701667/…
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.