DEV Community

Cover image for Using Rails Model or SQL query in Ruby On Rails
Sparsh Garg
Sparsh Garg

Posted on • Edited on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay