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