I have a page Aboutus - This has a Controller and View. Has no model.
I have a Comments model (generated by the rails generate scaffold
comment) - This has a Controller, view, model
On my Aboutus page, I want to show the "Comments" from the comments
model, so I am thinking of using the Comments index action (to list
comments) and new action (to create new comments) on my Aboutus page.
I am having trouble getting this right.
This is what I did: Aboutus controller, I added
redirect_to :controller => "comments", :action => "index"
Aboutus views, I added
<%= render 'comments/index' %>
It doesnt work, gives me Undefined redirect_to and nil object @comments
errors. Could you advise me
1. A proper way to do this
2. Syntax
3. Any thing to do to config.rb ?
You need to take the redirect_to out of the about_us action, and instead
just set an instance variable that has the comments that you want to
display.
# app/controllers/pages_controller.rb
class Pages < ApplicationController
def about_us
@comments = Comment.all
end
end
Then all you need to do is render the comments page.
# app/views/pages/about_us.html.erb
<%= render 'comments/index' %>
# app/views/comments/index.html.erb
<%= for comment in @comments %>
...
However, really you should put the part of the comments/index.html.erb
that is shared with about_us.html.erb into a partial, so that both views
can use the same code.
# app/views/comments/_all_comments.html.erb
<%= for comment in comments %>
...
'comments' is a local variable here, so you need to define this variable
when you call the 'render' method.