1

As a Rails Rookie I wonder what is the proper way to reuse code that interact with database objects. For instance I have:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all
  end

end

I also have a Welcome page with a Welcome controller:

class WelcomeController < ApplicationController
  def index
    @posts = Post.all
  end
end

I would like to ALSO show the same list of posts on the Welcome page. I implemented a partial view for Posts and used it in Welcome view, but repeating the same database query on Welcome controller seems to be the wrong way to do it since I am repeating myself.

I also called the other controller action like this but I don't know if this is acceptable.

class WelcomeController < ApplicationController
  def index
    @posts = PostsController.new.index
  end
end

I wonder if there is a right way (rails way) to share actions between controllers. In essence from WelcomeController call index action of PostsController so I don't have to implement repeat the method

Webert Lima
  • 8,637
  • 1
  • 9
  • 21
  • 1
    Initializing the controller like that is just not going to work. Controllers are essentially Rack applications so you would need to pass the env hash that contains the context of the request to the initializer. It's also very like the method won't return the value of @posts. It will return the result of doing an implicit render which is a response object. – max Apr 06 '20 at 03:39

1 Answers1

3

Good question!

It might seem like too much repetition, but it is totally fine to repeat the database query in the controllers. Don't instantiate a new controller instance and then call the index method on it like you did.

Remember that the HTTP requests get routed to the right controller action and then render a view. So refactoring same views into partials and rendering those is perfectly fine, but don't bother about repeated code in the controllers, especially if it is just a simple query.

Once your app will grow, you will have more code in the controllers and it won't look like repetition so much. If you have larger code blocks that are repeated, you can work with concerns (How to use concerns in Rails 4 they work for models, too).

max
  • 76,662
  • 13
  • 84
  • 137
Clara
  • 2,054
  • 3
  • 9
  • 26