How to create Active Record Models in ROR

Active record models are used to store and access data in a database. They create tables and enable modifications to be made to the tables.

If we want to create an active record model we have to inherit the ApplicationRecord class into our defined class.

class Student < ApplicationRecord

end

The above statement will create a class named Student. To create a table of that class in order to store some data, we can use SQL like this:

CREATE TABLE Student (
  varchar rollNo(11) NOT NULL auto_increment,
  name varchar(50),
  subject varchar(100),
  PRIMARY KEY  (rollNo)
);

So, a table with the three attributes rollNo, name, subject is created. Now, we can add data to tables as follows:

temp = Student.new
temp.name = "Behzad Ahmad"
puts temp.name 
temp.subject = "Software Engineering"
puts temp.subject 
Copyright ©2024 Educative, Inc. All rights reserved