Generating a migration from model
I am a beginner in Ruby on Rails and following the below article:- http://guides.rubyonrails.org/migrations.html
If I need to generate a migration and a model, I can use, for example :-
$ rails generate model Product name:string description:text
and that would create :-
class CreateProducts < ActiveReco开发者_开发技巧rd::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
However, If I have a bigger model (with many properties). I don't want to put all the properties in the "rails generate" command. Can I hand code the model first and then generate the migration from that model file?
Sorry for asking so stupid question. I am just trying to understand.
Generate command is not must to do thing. It's just a script which helps you to automate some job. What exactly this command has done you can see in console after running generate command. It looks like this:
rails generate scaffold User name:string email:string
invoke active_record
create
db/migrate/20100615004000_create_users.rb
create
app/models/user.rb
invoke
test_unit
create
test/unit/user_test.rb
create
test/fixtures/users.yml
route resources :users
invoke scaffold_controller
create
app/controllers/users_controller.rb
invoke
erb
create
app/views/users
create
app/views/users/index.html.erb
create
app/views/users/edit.html.erb
create
app/views/users/show.html.erb
create
app/views/users/new.html.erb
create
app/views/users/_form.html.erb
invoke
test_unit
create
test/functional/users_controller_test.rb
invoke
helper
create
app/helpers/users_helper.rb
invoke
test_unit
create
test/unit/helpers/users_helper_test.rb
invoke stylesheets
converted by Web2PDFConvert.com
create
public/stylesheets/scaffold.css
You can actually create/modify all files by your hand. But the benefit of using generate
is that it automatically invokes all necessary plugins and etc to generate all required files.
That's why it's recommended to use generate command even for very complicated models, controllers and etc.
So in your case I would suggest to divide the building the model in several steps. It could be like this:
rails generate model Product name:string description:text
rails generate migration AddPriceToProducts price:integer
rails generate migration AddDiscountToProducts discount:integer
and so on
Every step you could rollback in case if you made some mistake and it helps you to not harm your database.
You can hand-code the migration. The model's attributes are read directly from the database... so if you add t.string :name
to the migration file, and then run rake db:migrate
, that column will be added to the table, therefore making it available as an attribute on your model.
精彩评论