Jocker_mix
Jocker_mix

Reputation: 80

Rendering an Action's Template from Another Controller

I'm working on a porject that has the following design forums have posts which have comments. I am reading the ruby guidance http://guides.rubyonrails.org/layouts_and_rendering.html#overview-how-the-pieces-fit-together and it says to render an action template from another action I need to use something like this render "posts/index".

I am trying to print all the posts of a forum in that forum. I have set the database and model but not sure how to deal with the controllers.

How can I call posts/index in the forums/show/i ( where i is the id of forum ).

How can I print the posts in the forum and how can I print only the posts that are related to that particular forum ?

when I try to call render "posts/index" in the index function of the forum controller, I get this error message:

ActionView::MissingTemplate in Forums#show 


Showing /home/ubuntu/workspace/app/views/forums/show.html.erb where line #26 raised:

Missing partial posts/_index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/ubuntu/workspace/app/views"
  * "/usr/local/rvm/gems/ruby-2.3.4/gems/devise-4.3.0/app/views"

<%= render 'posts/index' %>

the above is highlighted red.

Thanks for your time.

Upvotes: 1

Views: 840

Answers (1)

Julian G.
Julian G.

Reputation: 143

Since you have the models associated to each other, i would do it this way. in your forum show view:

<%= render partial: 'posts/index', locals: {forum: @forum} %>

then create the partial view posts/_index.html.erb:

<% forum.posts.each do |post| %>
   <div><%= post.your_attributes %></div>
   <div><%= render partial: 'comments/index', locals: {forum: forum, post: post} %>
<% end %>

finally create a partial view comments/_index.html.erb:

<% post.comments.each do |comment| %>
    <div><%= comment.your_attributes %><div>
<% end %>

The locals option passes those variables to your partial to be usable there.

Upvotes: 1

Related Questions