Using Rails Model or SQL query in Ruby On Rails

sparsh9

Sparsh Garg

Posted on August 17, 2022

Using Rails Model or SQL query in Ruby On Rails

Although there can be multiple ways you can get data from your database, but here are two ways you can get data.

  1. Using Rails Model -> In this method of data fetching we use rails model, which we create using rails g model model_name.

So the code is as follows:

def index
    @data = ModelName.all
    render_success_response @data
  end
Enter fullscreen mode Exit fullscreen mode

In above piece of code

index -> name of the method

@data -> name of variable to store the data

.all -> rails method to get all the data from the respective table associated with the model

render_success_response -> default rails method to render a success response

Now there can be multiple methods we can use. Check out devhints for references.

  1. Using SQL Query -> In this method of data fetching we use direct SQL queries.

So the code is as follows:

def index
    sql = "select * from table_name"
    @data = ActiveRecord::Base.connection.execute(sql)
    render_success_response @data
  end
Enter fullscreen mode Exit fullscreen mode

In above piece of code

ActiveRecord::Base.connection.execute() -> it is used to run sql queries in ruby on rails.

Conclusion
You can use both rails model or sql query in you code according to your use case.

References
Dev Hints

💖 💪 🙅 🚩
sparsh9
Sparsh Garg

Posted on August 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related