I have used two different databases for my Rails application: MongoDB and MsSQL using Mongoid and activerecord-sqlserver-adapter adapter respectively. Everything is well but there is a problem while generate Model.
The problem is "how can I generate the model that relates to MongoDB or MsSQL differently?"
For example: I want to generate People model relates to MongoID and Animal model with MsSQL. While I generate with command: rails g model Animal name:string it generates the model related to mongoid. How can I generate the model Animal with ActiveRecord that means related to MsSQL.
Please help me.
Thanks
Based on Using Active Record generators after Mongoid installation? I believe this should work:
rails g active_record:model Animal name:string
First let me just check that I've understood your question correctly:
You have 2 databases and a series of models/migrations, and you want a way to tell rails which database to use when running a migration and accessing the database using your model?
If I'm in the right area then you need to add a method to your migration which overrides the default connection() method in ActiveRecord::Migration.
def connection
ActiveRecord::Base.establish_connection(:conn_name).connection
end
Where :conn_name is the name you gave your connection settings in config/database.yml
within your models add the line
establish_connection :conn_name
to the top of your model file and the model will now know which DB to connect to.
So the quick and dirty way that I have handled this in the past (due to my dev team keeping mongoid in the gem file for legacy reasons) is to comment out the out mongoid when you have to do migrations run a bundle, generate and run you migration then uncomment and run bundle again. This is far from best practices but it should work.
Related
I already have a database with the right structure.
I would like to create a rails app just to read into this database, I don't want to insert neither update etc...
Actually, I would like to use rails but handle myself the creation of the database and tables.
Is it possible ?
I've commented every lines into "create" def into the migration file, it works but is there another way ?
Thank you.
rails g model ModelName --skip-migration
You might be able to use this Gem.
gem 'rmre', '~> 0.0.8'
It allows you to create models from an existing schema.
See documentation here: https://github.com/bosko/rmre
I am trying to access all records of a table that has an underscore in its name.
For example if I have table in my schema that is called trips I can do Trip.all in rails console. But what do I do if my table name contains an underscore (e.g. users_foods)
I tried the following options:
Users_food.all
User_food.all
User_foods.all
etc.
All of the above did not work, any suggestions?
Figured it out
One can access the data with UserFood
For a table named users_foods, ActiveModel should provide you with a corresponding Rails model UsersFood, to fit Ruby/Rails object naming convention. Try that.
Class names Users_food or User_food, etc. do not conform to Ruby convention.
I had the same problem when creating bonus_histories table. And didn't work any of the answers until I found out why.
I have made only rails g migration BonusHistory
and it was the problem. My rails console didn't find BonusHistory at all because I had no model.
So I had to first rollback the migration rake db:rollback STEP=1, then deleted the migration file and finally made
rails g model BonusHistory
and after migrating that table, when I enter rails console, I can successfully ask for BonusHistory.count
I am new to Ruby on Rails . This might be a very foolish question.
I have created a migration using
rails generate migration Kapol name:string position:integer
rake db:migrate
Then using phpmyadmin i copied the database already present
I then opened up rails console
My question is can i use the method Kapol.find(1)??
because when i tried it using singular or plural it says
unitialized constant:Kapol
I know that there has to be a method but where to specify it?
You must generate a model in case to create a table for it, because the migration is usually used to modify existing tables.
It might be confusing that the model generator also creates migration file in your migrations folder. The only difference is that the model generator also generates initial code to create table, on the other hand, the migration generator creates only migration file without initial code.
rails generate model Kapol name:string position:integer
More information: http://guides.rubyonrails.org/getting_started.html#generating-a-model
If you're very new to Ruby on Rails, probably the best thing for you to do is create a scaffold, which gives you your migration file, your model file, your controller file, and various view files, test files, etc. etc., which all work well together. Then you can play with these and build up from there.
rails generate scaffold Kapol name:string position:integer
If you're happy with the migration that was automatically generated, then rake db:migrate and you're all set.
As Andrew says below, you can also just generate any of those files one at a time by replacing 'scaffold' with 'model', etc.
Your Kapol.find(1) is correct.
rails generate migration
rails generate model
rails generate scaffold
rails generate controller etc.
How these differ?
According to rails guides:
Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work, but not necessary for you to spend time writing. That’s what we have computers for.
rails generate commands family used to provide simple and easy way for developer to create different object types.
rails generate migration - creates DB migration script in db/migrations directory so developer can setup his DB.
rails generate model - creates model class with associated migration, test and fixtures (test data).
rails generate scaffold - creates all nedded classes with basic logic and presentaion. It creates controller (with simple CRUD logic), model, fixtures, functional and unit tests.
rails generate controller - creates controller with associated functional tests, helper and basic views templates.
You can read more here: http://guides.rubyonrails.org/command_line.html#rails-generate
They differ in the sense that they generate different stuff.
migration will generate a database migration file,
model will generate a model(with a migration and a spec by default)
scaffold will generate a scaffold of a resource
and controller will generate a controller.
generate means it will create the files for you with boiler plate code already in place(you will still need to edit them though..but scaffold can get you working with a basic application already)
Read more about it here: http://guides.rubyonrails.org/command_line.html#rails-generate
rails generate is a command line script for quickly generating the code for various Rails' constructs.
In the example you give they differ by what they produce, with the first argument being the type of code generated. For example if I wanted to create a User model I would run:
`rails generate model user`
The model file, test file and migration would be created for me.
You should read the Rails' documentation to find more.
**rails generate model user:
The above command create a Template Object that is a mirror image of the database table.
For example, if you have a database table that is named users that has a name:string, and email:string field,then "rails generate model user" create an Object that mirrors that user table with a few addition.
Here are the similarity they both have name:string,email:string the both have the word user.
The difference are few but significant: user is Capitalized in the model name like "User".
The Table add create_by and updated_by automatically.
migration:db create the database mirror using the model as a model.RECURSION ANYONE?
I have a bunch of rails models that I'm re-writing into a single model to simplify my code and reduce unnecessary tables.
I'm wondering what the best way to delete a model class and its table is. I want past migrations to still succeed, but I don't want to leave the empty models lying around.
Do I have to manually delete the old migrations that reference these models, then manually delete the class files?
Does anyone have any tips for the best way to do this?
All in one solution.
Run the following commands:
rails destroy model ModelName
rails g migration DropTableModelName
The former will generate a new migration file which should looks like this:
class DropTableModelName < ActiveRecord::Migration
def change
drop_table :model_name
end
end
Now run db:migrate and you're done.
If you'd like to completely get rid of of a model and its table do this:
rails destroy model Name
The question is a bit stale now, but I just did:
rails destroy scaffold <ModelName> -p
The -p flag shows "pretend" output, which is good for seeing what will happen. Remove the '-p' flag and the results will match the output. This cleaned the entire collection of M-V-C files + testing + js files + the original migration, no problem.
I guess if you are one who likes to hand edit your migrations and include multiple steps in each, losing the original migration could break db:setup, so buyer beware. Keeping one action == one migration file should avoid this potential snafu.
What about doing ruby script/destroy model? That should take care of the model and the migration.
Depending on how far into development or production you are, you may want to migrate the models out safely using a migration to remove/backup data or what not. Then as bobbywilson0 suggested, using
script/destroy model
or if you rspec anything
script/destroy rspec_model
This will remove any spec tests as well.
Or you can always just drag them to the trash folder.
You can take a look at this one at rails guide.
But I suggest, if it is possible, you should delete the models and all references to the models. This will probably save time later as you don't need to maintain the dead code in the codebase.
If you'd rather have a manual based answer:
First run the following command to identify which migrations you want removed:
rake db:migrate:status
Feel free to grep -i on it too if you're confident of your naming scheme.
Make note of all the "add x to model name" and similar alterations to your Model. These can be removed using:
rails d migration AddXToModelName
Do this for every migration besides the initial create migration. The following command will take care of the initial create migration and the files associated with the model:
rails d model ModelName