0

This might be easy but i am not sure about this as on beginner level in rails.

learning rails model through a tutorial i found this --

Use t = Todo.new to create an empty row in the Todo table and stores it in t 

After this i run the following command -

> t.todo_item = "Assignment 1"
=> "Assignment 1"

and t.save saves data successfully. Upto this point i am ok with it, however when i executed Todo.all command its showing only single row, i was expecting 2 one from the initial with id nil.

So is that the initial blank row that created while object creation destroys after second command run on db or is that something else.

Is nil values in rails/ruby refer to the NULL? (As this is what i got from Todo.new [ id:nil todo_item:nil ...] )

2 Answers 2

1

The object isn't saved to the database when you call t=Todo.new. It just creates an object in memory.

Calling t.save writes the record to the database.

You should be able to keep your sanity by doing this:

n = Todo.all.size # size of table before changes
t = Todo.new # create new object
t.todo_item = "Assignment 1"
t.save # save it to db
Todo.all.size==n+1 # should return true
Sign up to request clarification or add additional context in comments.

2 Comments

is nil same as NULL (as iam from php/mysql background so not sure they are same or not )
nil is a Ruby term that can be considered equivalent to a NULL value in a database.
1

t.save persists t to the database, and id is populated. Assuming you're using ActiveRecord, the id field is an automatic field and is auto-incremented. If you have a Todo with a nil value for id, that would indicate that object has not been persisted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.