Reputation: 551
I am new for Ruby on Rails, I want to create model and CRUD if my database is already created. I am using mysql database.
Thank you,
Upvotes: 3
Views: 8965
Reputation: 209
This is an old question but the answer provided here doesn't work for me as I wanted everything you can typically scaffold. I was trying to find out myself and here's how.
class Person < ApplicationRecord
end
rails generate scaffold_controller people
The scaffold_controller
command is the key, it's not a command you see appear in googled examples!
Upvotes: 0
Reputation: 330
Upvotes: 0
Reputation: 3126
You can use rails generators to create a scaffold, which will create model, controllers with all CRUD methods and basic views for you, implementing the CRUD actions.
For example, lets say you want to create a student model with name, age and address fields in your database, you'll generate like this
rails generate scaffold Student name:string age:integer address:string
This will generate these files for you
app/controllers/students_controller.rb # StudentsController
app/models/student.rb # Student model
app/views/student/ * # all view files for your student model
db/migrate/migrations_file_for_student.rb
You can always create these files manually. And write its methods yourself. Let me know if it helps.
Update
If you have an existing database, make sure you write your you have set up your database.yml
file correctly, to connect your app to the right database.
Next create models, but not the migration files(hence you'll have to create user.rb
inside app/models
manually.)
Test if its working: Open rails console
and type
User.all #will list all existing users in the console
to see if everything goes well.
Next you need to create controller and views for your. You can create scaffold_controller
instead of controller
which also create views for you.
rails g scaffold_controller User email first_name last_name
This will create all the views for you, and users_controller
with CRUD methods, but no models or migrations files.
Hope this helps, let me know if there is anything else.
Upvotes: 2
Reputation: 10251
As you have already tables in db then no need of scaffold
or generate model
command, as it will generate migration file too.
simple create user.rb file under models folder.
class User < ActiveRecord::Base
end
then run
rails g controller users
this above command will create controller and views for it.
If you want to create new model and CRUD then
rails g scaffold ModelName field_name:data_type field2_name:data_type
above command will generate model, controller with CRUD methods, migration file and views
for more info http://www.tutorialspoint.com/ruby-on-rails/rails-scaffolding.htm
Note: I hope you have configure database connection via config/database.yml
file to use existing database
Upvotes: 3