Editing a form in nested_form gem

This is a very very naive and simple thing but I quite lost my time on this so I thought might be helpful.

Recently I was using the ‘nested_form’ gem by the great Ryan Bates (https://github.com/ryanb/nested_form). The form to create a new form works like a real gem without any effort.

Now, when I clicked on ‘edit’ link, it created some issues as the nested models didnt come.

I had a simple thing like each question has many answers. When I created a question, I added 5 answers to it but when I edited the question, no answers were visible.

The simple solution for this would be that the <% f.fields_for :answers do |an| %> line in your form would be without an equal to sign so just add it.

Thus, it looks like

<%= f.fields_for :answers do |an| %>

Thats all and it works like a charm!

Hope it helps.

Why not to use Strings in Cucumber

Cucumber allows you to define step definitions using strings instead of regular expressions.

This might seem simpler at first, but it has other problems, which I’ll illustrate with an example.

Here is a step definition that uses a plain string.

Given “I have 100 in my Account” do

end

We couldn’t write $100 here, because the $ has a special meaning when you define step definitions with strings.

Any $ signs—including any letter or number following it—will be interpreted as an argument, .

This step definition uses an argument:

Given “I have $amount in my Account” do |amount|

 

end

This step definition would match both of the following Gherkin steps:

Given I have 100 in my Account

Given I have $100 in my Account

 

In the first case, the Step Definition’s amount argument would have the value “100”. In the second case it would have the value “$100”. If our Step Definition expects a string with only digits, this can be problematic. We have no way to enforce a consistent way to write Gherkin steps, and the step definitions have to anticipate many kinds of input.

 

This is why using strings instead of regular expressions is not as advantageous as you might think. They give far less control over what gets matched and what arguments a step definition can receive.

Installing and setting up GIT

INSTALLING GIT
Installing from Source:
In short, on a Unix-based system, you can download the Git source code from the Git Download Page, and then run
something along the lines of :

$ make prefix=/usr all ;# as yourself
$ make prefix=/usr install ;# as root

You will need the expat, curl, zlib, and openssl libraries installed – though with the possible exception of expat, these will normally already be there.

Linux
If you are running Linux, you can likely install Git easily via your native package management system:

$ yum install git-core
$ apt-get install git-core

Mac 10.4:
In both Mac 10.4 and 10.5, you can install Git via MacPorts, if you have that installed. If not, you can install it from here.
Once MacPorts is installed, all you should have to do is:

$ sudo port install git-core

If you prefer to install from source, these articles may be helpful:
Article: Installing Git on Tiger
Article: Installing Git and git-svn on Tiger from source

Mac 10.5
With Leopard, you can also install via MacPorts, but here you have the additional option of using a nice installer, which you can download from here: Git OSX Installer
If you prefer to install it from source, these guides may be particularly helpful to you :
Article: Installing Git on OSX Leopard
Article: Installing Git on OS 10.5

SETUP AND INITIALIZATION
Git Config
The first thing you’re going to want to do is set up your name and email address for Git to use to sign your commits.

$ git config –global user.name “Rushabh hathi”
$ git config –global user.email “rushabhhathi@gmail.com”

That will set up a file in your home directory which may be used by any of your projects. By default that file is ~/.gitconfig
and the contents will look like this:
[user]
name = Rushabh Hathi
email = rushabhhathi@gmail.com

If you want to override those values for a specific project (to use a work email address, for example), you can run the git config command without the –global option while in that project. This will add a [user] section like the one shown above to the .git/config file in your project’s root directory.

Active Record

Active Record is a great example of the Rails “Golden Path.” If you keep within its limitations, you can go far, fast. Stray from the path, and you might get stuck in the mud. This Golden Path involves many conventions, like naming your tables in the plural form (“users”). It’s common for new developers to Rails and rival web-framework evangelists to complain about how tables must be named in a particular manner, how there are no constraints in the database layer, that foreign keys are handled all wrong, enterprise systems must have composite primary keys, and more. Get the complaining out of your system now, because all these defaults are simply defaults, and in most cases can be overridden with a single line of code or a plugin.

Database-Related Rake Tasks

The following rake tasks are included by default in boilerplate Rails projects.

db:create and db:create:all
Create the database defined in config/database.yml for the current Rails.env (Or create
all of the local databases defined in config/database.yml in the case of db:create:all.)
db:drop and db:drop:all
Drops the database for the current RAILS_ENV. (Or drops all of the local databases
defined in config/database.yml in the case of db:drop:all.)
db:forward and db:rollback
The db:rollback task moves your database schema back one version. Similarly, the
db:forward task moves your database schema forward one version and is typically used
after rolling back.
db:migrate
Applies all pending migrations. If a VERSION environment variable is provided, then
db:migrate will apply pending migrations through the migration specified, but no
further. The VERSION is specified as the timestamp portion of the migration file name.

If the VERSION provided is older than the current version of the schema, then this task
will actually rollback the newer migrations.

db:migrate:down
Invoked without a VERSION, this task will migrate all the way down the version list to
an empty database, assuming that all your migrations are working correctly.
With a VERSION, this task will invoke the down method of the specified migration
only. The VERSION is specified as the timestamp portion of the migration file name.

$ rake db:migrate:down VERSION=20100124181315
== AddClientIdToUser: reverting =========================================
— remove_column(:users, :client_id)
-> 0.0367s
== AddClientIdToUser: reverted (0.0370s) ================================

db:migrate:up
Invoked without a VERSION, this task will migrate up the version list, behaving the same
as db:migrate.
With a VERSION, this task will invoke the up method of the specified migration
only. The VERSION is specified as the timestamp portion of the migration file name.

$ rake db:migrate:up VERSION=20100124181315
== AddClientIdToUser: migrating =========================================
— add_column(:users, :client_id, :integer)
-> 0.0383s
== AddClientIdToUser: migrated (0.0385s) ================================

db:migrate:redo
Executes the down method of the latest migration file, immediately followed by its up
method. This task is typically used right after correcting a mistake in the up method or
to test that a migration is working correctly.

$ rake db:migrate:redo
== AddTimesheetsUpdatedAtToUsers: reverting =============================
— remove_column(:users, :timesheets_updated_at)
-> 0.0853s
== AddTimesheetsUpdatedAtToUsers: reverted (0.0861s) ====================
== AddTimesheetsUpdatedAtToUsers: migrating =============================
— add_column(:users, :timesheets_updated_at, :datetime)
-> 0.3577s
== AddTimesheetsUpdatedAtToUsers: migrated (0.3579s) ====================

 

 

db:migrate:reset
Resets your database for the current environment using your migrations (as opposed to
using schema.rb).
db:reset and db:setup
The db:setup creates the database for the current environment, loads the schema from
db/schema.rb, then loads the seed data. It’s used when you’re setting up an existing
project for the first time on a development workstation. The similar db:reset task does
the same thing except that it drops and recreates the database first.
db:schema:dump
Create a db/schema.rb file that can be portably used against any DB supported by
Active Record. Note that creation (or updating) of schema.rb happens automatically
any time you migrate.
db:schema:load
Loads schema.rb file into the database for the current environment.
db:seed
Load the seed data from db/seeds.rb as described in this chapter’s section Database
Seeding.
db:structure:dump
Dump the database structure to a SQL file containing raw DDL code in a format
corresponding to the database driver specified in database.yml for your current envi-
ronment.

$ rake db:structure:dump
$ cat db/development_structure.sql
CREATE TABLE ‘avatars’ (
‘id’ int(11) NOT NULL AUTO_INCREMENT,
‘user_id’ int(11) DEFAULT NULL,
‘url’ varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (‘id’)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 


I’ve rarely needed to use this task. It’s possible that some Rails teams working in con-
junction with DBAs that exercise strict control over their application’s database schemas
will need this task on a regular basis.

 

db:test:prepare
Check for pending migrations and load the test schema by doing a db:schema:dump
followed by a db:schema:load.
This task gets used very often during active development whenever you’re run-
ning specs or tests without using Rake. (Standard spec-related Rake tasks run
db:test:prepare automatically for you.)
db:version
Returns the timestamp of the latest migration file that has been run. Works even if
your database has been created from db/schema.rb, since it contains the latest version
timestamp in it:

ActiveRecord::Schema.define(:version => 20100122011531)

 

Database Seeding in Rails

The automatically created file db/seeds.rb is a default location for creating seed data for your database. It was introduced in order to stop the practice of inserting seed data in individual migration files, if you accept the premise that migrations should never be used for seeding example or base data required by your application. It is executed with the rake db:seed task (or created alongside the database when you run rake db:setup).

At its simplest, the contents of seed.rb is simply a series of create! statements that generate baseline data for your application, whether it’s default or related to con figuration. For example, let’s add an admin user and some billing codes to a sample app:

User.create!(:login => ‘admin’, :email => ‘admin@tr3w.com’,:password => ‘123’, :password_confirmation => ‘123’,
:authorized_approver => true)

client = Client.create!(:name => ‘Workbeast’, :code => ‘BEAST’)
client.billing_codes.create!(:name => ‘Meetings’, :code => ‘MTG’)
client.billing_codes.create!(:name => ‘Development’, :code => ‘DEV’)

 

Why use the bang version of the create methods? Because otherwise you won’t find out if you had errors in your seed file. An alternative would be to use find_or_create_by methods to make seeding idempotent.

c = Client.find_or_create_by_name_and_code!(‘Workbeast’, ‘BEAST’)
c.billing_codes.find_or_create_by_name_and_code!(‘Meetings’, ‘MTG’)
c.billing_codes.find_or_create_by_name_and_code!(‘Development’, ‘DEV’)

 

Another common seeding practice worth mentioning is calling delete_all prior to creating new records, so that seeding does not generate duplicate records. This practice avoids the need for idempotent seeding routines and lets you be very secure about exactly
what your database will look like after seeding.

User.delete_all
User.create!(:login => ‘admin’, …
Client.delete_all
client = Client.create!(:name => ‘Workbeast’, …