When to use models and migrations in Ruby on Rails - ruby-on-rails

rails g migration MigrationName
rails g model MigrationName
I know these two commands. I am confused when to use which command as function of both look similar.
Also how those files created by them are different.

If you run rails g model ModelName then you'll get a result similar to the following:
rails g model User
invoke active_record
create db/migrate/20200430143738_create_users.rb
create app/models/user.rb
invoke test_unit
create test/models/user_test.rb
create test/fixtures/users.yml
As you see, it creates a model file (in this case User), the migration file automatically named as create_yourmodelname_plural, plus a test file and a fixture for the model.
On the other hand, if you run rails g migration MigrationName, you are just creating a migration file. So, if you were to create a user table, you'll get a similar result:
rails g migration CreateUsers
invoke active_record
create db/migrate/20200430144301_create_users.rb
In conclusion, the first case can be used when you do not have a model nor the corresponding table in the database: you can easily create both a model file and a migration file with this automatically prefilled content (in this example the model is User):
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
end
end
end
The second case is used instead for specifically creating just a migration file - for any purpose (updating or even deleting a table, for instance), not only the creation of a new table.
I hope this can help :)

Well the main difference is that the second one should be rails g model ModelName doesn't just create a migration, but also creates a model file and a spec file for that model. It also will most generate a create table migration, whereas with rails g migration MigrationName, you can just do very specific migrations such as adding an index, or adding/removing columns. Sections 2.1 and 2.2 will help you get a better grasp: http://guides.rubyonrails.org/migrations.html

Related

Create a Users model where previous Users model existed then dropped

I am working on a Rails application where the previous developer had created a Users model, then later dropped it in lieu of another solution. The migration files are still in the repository, but obviously the table doesn't exist. I am now trying to create a User authentication system to integrate a blog, but I am running into the issue of the previous migration and getting the following error message when trying rails g model User:
"Another migration is already named create_users..."
Is it possible there a way to create Users again?
Just to be extra clear. There is a create_users and later a drop_users migration.
1. $ rails g model User --migration=false
2. $ rails g migration create_users_again
3. open create_users_again migration file (created in step 2), and define your table as:
def change
create_table :users do |t|
t.email :string
t.timestamps
end
add_index :email
end
You can look your old create_users migration file for help.
When the previous developer ran rails g model user, this created a migration class like so:
class CreateUsers < ActiveRecord::Migration
Now that you are running rails g model user, Rails is complaining that that class CreateUsers, already exits.
You can either:
Rename the previous migration to CreateUsersPrevious (don't forget to rename the migration file as well xxxxxxxxxxx_create_users_previous.rb) if you would like to keep it documented in your migration history
Remove the old migration file

create migration for model that in subdirectory

I have a 'question' model in Subdirectory Exceed::Question.
now I want to add migration for Question model, so I run
rails g migration AddImageToExceedQuestions
after that when I run `rake db:migrate
Its show error -
Mysql2::Error: Table 'bs_development.questions' doesn't exist: ALTER TABLE `questions`
In my database question model save as exceed_question.
I also try rails g migration AddImageToQuestions and rails g migration AddImageToExceed::Questions but get same error.
How I can create migration for model that in subdirectory.
In ActiveRecord migrations are not actually tied to model classes. They simply modify the schema and database tables but do not care about if your models actually exist at all.
The rails generators are smart enough to recognize some forms such as rails g migration AddNameToFooBar name:string which would generate:
class AddNameToFooBar < ActiveRecord::Migration
def change
add_column :foo_bars, :name, :string
end
end
Rails will recognize that the part after to is a table name and snake case it. And then pluralize the last word if it is singular.
rails g migration add_name_to_foo_bar name:string creates an identical migration. The same with rails g migration add_name_to_foo_bars name:string except for the file & class name of the migration.
You can fix your issue by opening up the migration file and ensuring that it has the correct table
class AddImageToExceedQuestions < ActiveRecord::Migration
def change
add_column :exceed_questions, :image, :string # or binary
end
end
Note that your table should be named exceed_questions, tables in rails use the plural form of the table name.

Creating an empty table, with fixed columns - Ruby on Rails

I'm very new to ruby on rails, been trying to play around with it in the past few days.
Basically trying to: Create a empty table, with fixed columns - Ruby on Rails
I've created a model like so:
rails g model table
rails g migration table
my tables.rb files looks like this:
class Tables < ActiveRecord::Migration
def change
add_column :table, :firstname, :string
add_column :table, :lastname, :string
end
end
(hopefully I created the columns okay)
I then run:
rake db:migrate RAILS_ENV=development
but seem to get an error no such table: table (but I thought I created it ? )
Also what is a good view I can use to see my table on localhost:3000, in a html.erb file?
What you are displaying as your tables.rb file is a migration file, not a model. Models are stored in app/models. Migrations are in db/migrate and have a name that is a datetime stamp followed by the migration name.
Your migration is performing add_column. You can't add_column until you create_table. That migration should have been built using "rails g model table". Please show all migrations with the entire filename.
Check the document that dax provided. The rails generate command uses a stylized command line. Many standard migration functions, such as creating tables and adding columns, can be automatically generated by using the correct migration name. For example:
rails g migration add_url_to_feed url:string
This will create a migration that adds a string column called url to the feed table.
Generally, migrations should do what you need. However there is another command, rake, that you will need. The reference is here. For example:
rake db:create # Create the database from config/database.yml for the current Rails.env
can create the database for you.

changes to model in ruby on rails

All,
I need clarification on how model changes need to tracked in ruby on rails. I started off by creating a model with say two fields, name and email. Here is what i have done
Created a model by running
"rails generate model user first_name:string last_name:string"
This created a model file
I then added some validations to the files created in user
Used the annotation gem to annotate the class
used "bundle exec rake db:migrate" to move my model to database which created the tables
I now want to add a couple more fields to the model. What steps do i need to follow?
Do i add columns to the database and run some command so that the model(class) is in sync with the db?
Do i delete and recreate the whole model with the new fields?
what is the recommended approach
Venu
You want to use a migration to update the existing table, you can do the entire process from the command line
Assuming you've done
rails generate model user first_name:string last_name:string
previously you would add fields like so;
rails generate migration AddFieldsToModel new_field:string another_field:string....
Rails does magic on the 'AddFieldsToModel' and works out the table name from the value for you.
Once you've created the migration you can look at it in db/migrations and then if you're happy with it just run
rake db:migrate
this will update your database to add the new fields to it. You don't need to do anything to the actual model.rb file - but you will need to re run the annotate task to have it reannotated to the model.rb file.
I am not sure what version of rails your are using .. but int rails 3.x it can be done as
rails generate migration add_fields_user
this creates a file in db/migrate/[timestamp]/add_fields_user.rb
now you can write in the file and run rake db:migrate
add_column :users , :city, :string
What you want to do is run a migration by typing. rails generate migration description_of_migration. This will create an empty migration which you can define what you want to add to your model. In your case it may be something like this:
class DescriptionOfMigration < ActiveRecord::Migration
self.up
add_column :users, :email, :string
end
self.down
remove_column :users, :email
end
end
This makes it so you can migrate both ways on the model.

scaffolding and updating attributes manually in ruby on rails howto?

I was wondering if anyone knew how to update the files (adding/removing/updating an attribute) produced by using the scaffold generator in ruby on rails.
For example:
scaffold student name:string lastname:string
so this will create a the associate files (controller,view,etc) with name and lastname as string attributes. When you db:migrate the project, it'll create the table in the database. However, say I want to update whether it be update it with an addition attribue (ex. studenId:integer) or if its removing or updating an attribute, how do you do that?
I tired just updating the generated files, but when I do that db:migrate it still sets the schema that is generated to what is in the table. Is there a built in script in rails that will update the table?
Any advise appreciated?
Thanks,
D
Full command in this example:
$ rails generate migration add_studentid_to_student
You need new migration file for new attributes, from console:
$ script/gnerate migration add_sudentid_to_sudent
it will generate your_app/db/migrate/8293898391_add_sudentid_to_sudent.rb, spicify in this file your new attributes:
def self.up
add_column :sudents, :studentId, :integer
end
def self.down
remove_column :students, :studentsId
end
after that, back to console:
$ rake db:migrate
and than you can edit your views, model, controller files and use new attribute
Hi Try ruby script/destroy scaffold student and then ruby script/generate scaffold student
also try reading up on rails migrations, for dropping/updating table columns.
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Resources