RoRails
RoRails

Reputation: 45

Rails: Combining Multiple Controller Actions with their own Views into a Single View

I have two different controllers with their own feed(index) actions and I want them to be displayed on a single page (home). The posts and requests models are not similar and hold different types of data (images, video links, strings, etc.).

In my posts controller I have this action. It uses two API actions in the same controller and fills a @post_array with specified record information which then gets displayed in the posts/feed.html.erb view:

    def feed
      if user_signed_in?
           post_feed_authenticated
      else
           post_feed_not_authenticated
       end
    end

In my requests controller I have a similar action that returns a @request_array with all relevant request records and displays them in requests/feed.html.erb.

    def feed
       request_feed
    end

The methods the actions call filter all records by location, authentication, and IDs.

I've already created separate views for these actions that work correctly, but I want to combine them so both feeds are shown on the same page (home.html.erb). How do I go about doing this? I've read into using partials but I am not sure if that is applicable here since the data is different.

Edit: The home controller is:

    def home_page
    end

The home_page.html.erb currently has buttons to the corresponding post/request feed. I want to put both feeds on the home_page.

Upvotes: 0

Views: 1651

Answers (2)

Dani
Dani

Reputation: 1022

As I understand it - you want to reuse both the views and the code that populates @post_array and @request_array in your home view. I see these as two different concerns with different solutions:

  • For reusing the views you can use partials. By having partials for the posts feed and the request feed you could reuse the view in the home view.
  • And for reusing the way you populate the @post_array you could try and place that logic in somewhere where your HomeController has access to, ideally your Post model (i.e. Post.feed(current_user, location)) or a service object. Another, hacky way to do this is by placing these methods in the ApplicationController, making them available in all controllers.

Upvotes: 0

hashrocket
hashrocket

Reputation: 2222

You can create instances of each class in the index action of the home controller:

@posts = Post.all
@requests = Requests.all

Then you have access to all variables and methods in each class.

(Change index from above to whatever you named your home page.)

Upvotes: 0

Related Questions