Rails model generator - from existing database - ruby-on-rails

Is there any working automatic model generator for creating a model from existing database?
Something like symfony's task symfony doctrine:build-model.
I found just Dr Nic’s magic model generator but it doesn't work with rails 2.3+. Please do not recommend Dr Nic's magic models. That's not what I want.
I don't believe that there is nothing else for such a common task.
EDIT: I don't want to generate just empty models. I want to also automatically generate associations and validations.

Hey there. This is quite a simple procedure to do;
Modify your_project/config/database.yml with connection params so that it connects up to your existing database.
For each table you wish to turn into a model type the following:
script/generate model tablename

Related

how to create new rails generator for dropping a table

I creating an app that needs to be able to create and drop tables on the fly, on create it's pretty simple I use:
rails g model User name:string
but there is no generator for dropping a table.
I want to make it be possible to:
rails g migration DropTableUser
To correct your question, rails g migration User name:string would result in a migration called User not a model, I guess what you meant was rails g model User name:string.
To answer your question, I think it would result in an unnecessary mental effort, especially since something like this already exists in:
rails [d|destroy] model User
If you want to still implement yours, I'd advise that you look at Rails Generators instead for a way to help you out. I guess that would be dependent on creating a migration template etc.

Command to create database tables(with fields and relationship) based on model

Is there a way to specify the fields and relationships in the model and run a command to the rails create tables in the database based on the models, and then I can create or remove other fielda, change some relationships and run this command again and rails do update the tables in the database? I thought the migrate did it but after I read about it seems that it only creates the tables once and has no concept of model / db sync that i need.
No you need to create a new migration anytime you need to update the database. Changing some code in the model will not generate a migration.
No, but if you want a simpler way to write your migrations etc, I suggest you read more about the generators :)
For example :
rails generate model user first_name:string last_name:string birth_date:datetime friend:references
will directly generate the migration with the correct fields :)
And if you want to add a field after, you can write it like :
rails generate migration AddPseudoToUsers pseudo:string
And it will be correctly written normally :)
This is the doc
http://guides.rubyonrails.org/migrations.html#creating-a-migration
http://guides.rubyonrails.org/command_line.html#rails-generate

Rails Generating Migrations From Model

I've been reading about Rails Migrations to help me start building a rails project.
I'm a bit confused on the generation of the files in db/migrate.
The way I've been designing my application is by starting with the models... outlining all of the objects that I'm going to have in the system as best I can. I would like to generate the migration files FROM these models automatically with the rails migration generator.
Yes, I know "creating migrations manually is easy." And I know I could do it manually, but what I don't understand is why the tool is separated from the pre-created models.
Based on my understanding from the article and other migration questions on SO, I can generate a migration like so:
rails generate migration SomeObj field:string some_other_field:integer
What I don't get is why I need to pass in the fields when my model already exists for SomeObj? Couldn't Rails detect it from the some_obj.rb and create the migration from there?
Also, when I have a more complex model, with has_many, belongs_to, and has_to_and_belongs_to_many relationships, it would be really nice if it autocreated the JOIN tables and fields with the correct names (e.g. foreign_obj_id, foreign_obj_ids)
In a previous project I didn't have to deal with migrations because I used Mongo+Mongoid - and collections were automatically generated due to the nature of how Mongo works (collections that doesn't exist get automatically created upon inserting or updating). Now with this Rails app I'm using Postgres (but I'm sure the same thing would happen with MySQL or any other relational database).
Anyway, is there no helper for this kind of thing? Do I have to create all these migrations manually?
You've got this backwards. You need to build your migrations first, and your models second. Migrations advance the state of the database. Your models reflect the current state of the database. There is not a 1-to-1 mapping of models to migrations.
I would like to generate the migration files FROM these models automatically with the rails migration generator.
Can't be done.
You use rails generate migration to generate the migration, which, almost as a side-effect, generates a stub model file. You cannot use your existing model file to generate the model's migration, because the model doesn't contain any information about the actual columns that make up the model. Rails would have to extract and imply all the necessary information from your associations/validations, and even then it would get most of the columns wrong.
Also, when I have a more complex model,... it would be really nice if it autocreated the JOIN tables and fields with the correct names
Again, you can't. You're responsible for defining your database schema, and the way you do so is by building migrations. You can do so manually, or via rails generate, but the process you should be following is building your migrations first, and your models second.
By way of example, here is a complete model, ready for production:
class MyModel < ActiveRecord::Base
end
That model definition might wrap a table that contains 10 columns or 1000 columns; you (and Rails) have absolutely no way of knowing based on the model definition.
Here's another model, which contains at least one column, but again, you have no way of knowing what kind of column:
class MyModel < ActiveRecord::Base
validates :code, presence: true, uniqueness: true
end
Is code a string or a number? Should there be an index on the column? There is absolutely no way of knowing.

What is the common way to define models in Rails application?

All of the tutorials I've seen so far for RoR have shown me generating models like:
rails generate User name:string placeofbirth:string
This generates a class for the model, and only actually references an attribute if I apply a validation of some kind.
So my question is, how do I use a 'code' first approach when creating my models. Or is it the rails way to just right down on paper the attributes you want, run the generate command with each attribute you want and it's type, then run the rake db:migrate command?
I'd love some more proven patterns on this subject because so far the way I've seen seems too empty.
Yes, this is the rails way- migration comes first and generates the code and the database- and the model class inspects the database to see what fields are there and make accessible via methods.
You can do gem install annotate_models if you want to get some comments in your model class with the attribute names and types.
See here for an example: https://github.com/ctran/annotate_models
Rails uses an active record pattern for models which basically means that a model object will automatically map each DB column to an attribute so you don't have to specify all attributes in the model. It's a feature, but I agree that it might not be perfect for everyone. If you're using Rails 3 it should be easy to use another ORM of your choice if ActiveRecord's approach doesn't suit you. Here are some alternative ORMs that you could use.
Usually when you are developing some database backed web application, you know the database design(name of the tables, name of the columns in those tables and associations between different tables) beforehand.
Rails, as mentioned by maarons in his answer, uses Active Record pattern. Your models are classes that represent a table in your database, an instance of your model class a row in that table and different attributes of an object represent values under different columns in the same table.
When you create a model, usually, you are creating a class that represents one of the tables in your database. And while you are creating a model, you are also going to create a table in your database. That means knowing the name of the table and columns within that table.
So to answer your question, you must know all the columns, required for the time being, that will be in your tables. And hence available as attribute methods for your model objects. You specify these columns to added in the table in the migration generated by rails generator while generating this model. This is what usually everyone does.
You can take a code first approach by creating a class, without running the rails model generator,under app/models/ but not inheriting it from ActiveRecord::Base. As you move forward in your development, you can generate migrations by $ rails generate migration MigrationName and creating table and adding columns using [add_column][2]to that table as required. Once you have created a table for this model, you will have to inherit that model from ActiveRecord::Base so that you can get all the Rails magic in your application.

rails HABTM migrations

From a practical and best practices perspective, should rails models that have HABTM association also have a defined model for example users_groups.rb. So, should you
script generate model ...
or simply
script generate migration ...
On one hand the join table is simply two fields and shouldn't have any methods of its own, on the other hand, in rails (model = table). So would it be wise to have it defined in models as well as in migrations?
Hi as for me if you have has_and_belongs_to_many you don't need any model but if you use has_many+:through you'll need one

Resources