stergosz
stergosz

Reputation: 5860

ruby on rails should i query to db from controller

I am just getting started with Ruby on Rails and i am not sure how i should do the queries to database in order to get data, add data or edit data...

Is it better to find for example a user from the controller or its better to add the queries into the model?

currently, my user homepage controller looks like this with some simple functionality

class HomeController < ApplicationController

  #get current_user variable
  helper_method :current_user

  def index
    if user_signed_in?
        @user = User.find_by_id(current_user.id)
    else
        render_404
    end
  end
end

it simply checks if the user is logged in and finds the user...

Should i move the db calls to a model for best practice or using the above method is also fine?

Upvotes: 1

Views: 2148

Answers (2)

Erez Rabih
Erez Rabih

Reputation: 15808

The way you did it is fine in my opinion. The controller's job is to set the data for the view and part of setting the data is fetching it from the DB.

For more complex DB query you could use scope which are located in the model. This way the controller does not hold too much logic of DB queries on the model.

Upvotes: 2

amsprich
amsprich

Reputation: 201

You usually want to use a repository pattern which rails gives us by default with active record. I'd say that's perfectly fine. If you had more complex business logic or were pulling from multiple tables, then I'd probably move it into it's own class.

Upvotes: 2

Related Questions