Home Rendering an Action's Template from Another Controller
Reply: 1

Rendering an Action's Template from Another Controller

Jocker_mix Published in 2017-12-01 21:22:13Z

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.

Julian G.
Julian G. Reply to 2017-12-01 22:21:40Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.396922 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO