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.
Related
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
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.
How do I create a new field in an existing table using the Ruby command prompt?
I created the model (and migrated it) but I forgot to add a field - how would I go about this?
Generate a new migration to add a new column to table.
rails g migration add_column_name_to_table_name column_name:type
This will create a migration class like below:
#config/migration/20150304121554_add_column_name_to_table_name.rb
class AddColumnNameToTableName < ActiveRecord::Migration
def change
add_column :table_name, :column_name, :type
end
end
Here, column_name, table_name and type should be your desired name and type. Than run rake db:migrate command.
There are two ways to make changes in your situation:
Roll back the last migration
Add the new field in a new migration
Undoing the last migration should only be done if you have not yet pushed the migration to a public server. Here's how to do it:
Run rake db:rollback
Add the new field to the same migration file you originally used
Run rake db:migrate
Option 2:
To add the field in a new migration:
rails g migration AddFieldNameToTableName
For example, if your field is name and your table is users, you would run:
rails g migration AddNameToUsers
This will create a new migration file whose name starts with today's date and ends with add_name_to_users.rb. Open the file and add the field using the add_column command, like this:
class AddNameToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
end
end
Save the file, then run rake db:migrate.
I encourage you to read the Rails migrations guide to learn more.
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.
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