Having trouble getting started with Ruby on Rails - ruby-on-rails

I'm wondering if someone can address some of the issues I am having? I create a rails app:
rails myapp -d mysql
cd myapp
haml --rails .
rake db:create:all
Then I want to use a mysql client to create tables. Lets say users and customers. A customer is also a user so you have schema like this:
users
----------------
id int, not null, primary key, auto increment
first_name varchar(50) not null
last_name varchar(50) not null
email varchar(50) not null unique
password varchar(50) not null
created_at datetime not null
updated_at datetime not null
customers
----------------
id int, not null, primary key, auto increment
user_id int, unique
-- some other stuff that is customer specific
what rails script commands do I need to run to get model, views and controllers created and completely filled out under my rails app? I tried this:
ruby script/generate scaffold user
ruby script/generate scaffold customer
which creates the files but the models are empty:
class User < ActiveRecord::Base
end
whats the deal? Also, I want to create an administration section to manage stuff. I figured out that I need to add routes for those:
map.namespace :admin do |admin|
admin.resources :users
admin.resources :customers
end
what else do I need to get the administration section going?
Also here are the versions of ruby/gems I am running:
ruby 1.8.6
rails 2.3.5 & 2.3.2 <- I'm using 2.3.2 because haml
wasn't working (or some other plugin) with 2.3.5
haml 2.2.15
rspec 1.2.9 <- I saw from another thread that I might need
this when creating an adminstration section (rspec_controller etc)

Models are supposed to be empty by default because database schema is saved into the schema.rb file and managed using migrations.
From your answer I understand you are looking for a prepackage solution to write a couple of configurations and get everything, from controller to administration cooked for you.
I'm sorry, Rails doesn't offer you this feature. If you want an administration section you actually have to code it.
It includes:
creating your views and templates
creating your actions
mapping your routes
writing your tests
The scaffold only provides you a starting point but this is a starting point you should adapt and extend to your needs.
If you want the scaffold to auto-generate your initial views according to your database table, you can pass the arguments to the command line tool
ruby script/generate scaffold user name:string age:integer
But if you want to add a new field later, you'll have to write a new migration and edit your views/actions accordingly.
More information are available in the Rails Guides and Wiki.

Rails is designed for database independence with all the 'creation' done via the migrations located in db/migrate.
To create the appropriate DB tables you then simply run rake db:migrate and any migrations will be executed to create the necessary DB tables.
A good place for more information is the Rails Guides which has an example application to work through.

Related

How to change default join table name in rolify.rb?

I have dim_user, dim_role and role_user_map tables. I am using rolify gem for authorisation. I don't have role_id as primary key. In my case role_name is the primary key and my role_user_map table will have 2 columns (user_id, role_name) How to change default join_table name and other table names in rolify.rb?
I'm not familiar with it but I did some reading on the Rolify github page The dim_role dim_user and role_user_map tables you had already before you installed the rolify gem? You're supposed to use the gem's generator to create the role model using the syntax rails g rolify You could pass in DimRole and DimUser as arguments instead of just Role and User but again, you're supposed to be letting the gem create the mapping table for you, not having already created it yourself
Look at /db/schema.rb and see the structure of the tables created by the gem then modify and or rename your existing tables to match what the gem expects their structure and names to be Seemingly if you have pre-existing map or "through" tables you're gonna have to fool the gem Create a temporary app and run the gems generator with the names of your pre-existing tables (i don't know if the gem runs migratoins, if not then you have to run rake db:migrate after) then examine the created tables in schema.rb Then go back to your development app and restructure the tables to match the tables in the temp app

Rails with two different Databases

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.

Rails - generate Scaffold with Table Options

I've started learning Ruby last week, and I've started learning Rails today, so bear with me.
I see that Rails come with generators that allow you to generate models/controllers or even model+controller+views bundle as 'scaffold'. This is what I am interested in.
However, I have a question. How do I set database options of the column?
eg. To generate a users table I would do:
rails g scaffold users uuid:binary name:string email:string password:binary registered_on:date number:integer default:string
Now what if I'm integrity freak and am not happy by having validation just in model/controller, but want to do database level limitations as well.
What if I want email to be 50 characters max, and number to Auto-Increment and neither of all fields is allowed to be NULL and default field must have a default of 'foo'. Is there any way to pass these requirements to generator command?
I know its possible to set these options in .rb file that is used in rake db:migrate, however it would be easier to just pass values in with 1 command.
At least some things are available, like string length, but not sure about the others.
rails g scaffold users email:string{50}
Use type modifiers between curly braces, example:
rails generate migration AddDetailsToProducts price:decimal{5,2}
More info: migrations
Use scaffold and obtain generic migration files. And, as you mentioned, do the customizations in there. This files are found in db/migrate.
After you are done customizing the fields, don't forget to do a rake db:migrate.

Ruby on Rails existing Sybase database

I am trying to connect to an existing Sybase db using Rails and populate a few selection lists. Here's what I have done so far:
1. Installed and configured FreeTDS
2. Installed TinyTDS gem
if I execute command tsql -S serverName -U userName, I'm able to query the data. I have my config/database.yml configured as such:
development:
adapter: sybase
host: <sybase_host>
port: <port_no>
username: <user>
password: <password>
database: <db>
I then tried generating a model via rails generate model sybase_db --skip-migration and editing the created app/models/sybase_db.rb file as follows:
class SybaseDb < ActiveRecord::Base
set_table_name "my_sybase_table"
end
When I try to run SybaseDb.new command in rails console, it doesn't seem to work. I'm pretty new to Rails so what am I doing wrong?
Thanks!
Everything looks right up to the part where you generate a model called sybase_db. A model in Rails is typically linked to a specific table in a database, not the whole database. Rails uses naming conventions to simplify the linking of tables and columns to models and attributes.
For example, if you have a model User with attributes name and email that is linked to a table in your database called users and having columns name and email then all sorts of wonderful Rails magic just works. You could start the rails console and execute User.all to produce a collection of all users in the database. Or you might do something like
> u = User.find_by_email 'joe#example.com'
=> #<User id: 123, email: "joe#example.com", name: "Joe"...>
> u.name
=> "Joe"
If you have an existing database, however, chances are you're going to have to explain in more detail to Rails how to map the names in Sybase to those in your Rails system. You have one case of this in set_table_name -- if your Sybase table was named t_user with a primary key of user_id but it had columns name and email then you could create a Rails model like
class User < ActiveRecord::Base
set_table_name "t_user"
set_primary_key "user_id"
end
Here's a discussion of this topic on Quora with a couple good links that you might use to go further.
Depending on how extensive your existing system is, you may find that all of the magic of Rails goes away. Rails helps us avoid all of this mapping this to that, and follows strong naming conventions to give us all sorts of wonderful coolness. If your existing system has strong and predictable naming conventions, and isn't terribly far off from Rails' way, you might be able to use Rails successfully.

Model from existing table in Rails 2

I have a database with tables. I want to create a model in my Rails app from existing table. As i know, such functionality is available, and is done as follows:
script/generate scaffold model_name --skip-migration
Of course, i defined my database in database.yml file. Scaffold generated for me a model with controller and views. My table name is not as it must be for Rails(it is incorrect, not following conventions), i added set_table_name to my controller. But, when i am calling the index method, on my page i have only set of # symbols, but not a data from database. In my index.html.erb i have only generated code by scaffold. How can i print out my database data?
Have you generated a schema file from your existing database? If you run the command
rake db:schema:dump
and then re-generate your scaffold this should fix the problem.
Additionally you may wish to check out Dr Nic's Magic Model generator. This will generate models for all of your existing tables and attempt to guess the relationships. This will probably not work if your table naming is not understandable by rails.
UPDATE
I do not generally use the default scaffold however I have tested this myself and it appears that if you skip the migration and do not pass any column name/type pairs then the scaffold generator will not create anything in the template to render the columns.
You have two choices here either
Pass in the column name pairs as well as skip-migration or
Download Ryan Bates Nifty Scaffold generator which will create the scaffold with the column names even if you specify --skip-migration

Resources