Glyph
Glyph

Reputation: 85

How to use one layout by two different actions in rails 4

I'm building a micropost rails app where users can create posts, I created a route and an action to display posts that belong to the signed-in user, happens that the general index layout for posts is exactly the same as the "myposts" layout so instead of duplicating code I would like to use just one layout with different parameters. This is what I have until now:

routes.rb

resources :posts 
get '/myposts', to: 'posts#my_posts', as: 'myposts'

posts_controller.rb

def index
  @posts = Post.all
end

def my_posts
  @myposts= Post.where(user_id: current_user.id)
end

index.html.erb

<% @posts.each do |post| %>
  <div>
    <h1><%= link_to post.title, post %></h1>
    <%= link_to image_tag(post.meme_url(:thumb)), post, :target => "_blank"  %>
  </div>
<% end %>

my_posts.html.erb

<% @myposts.each do |post| %>
  <div>
    <h1><%= link_to post.title, post %></h1>
    <%= link_to image_tag(post.meme_url(:thumb)), post, :target => "_blank"  %>
  </div>
<% end %>

Thanks in advance!

Upvotes: 0

Views: 29

Answers (1)

Fist
Fist

Reputation: 397

You can use 'render' on 'my_posts' action - http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

Add before 'end' in my_posts action: render :index

Upvotes: 1

Related Questions