Reputation: 11
I am pretty new to rails and I am trying to display all the posts made by a user in my app.I did go through similar posts in this forum but did not succeed. I did some scaffolding with name , title and content attributes and then created a model called Blogger with 'name' attribute.
Here's my code
Controller
class BloggersController < ApplicationController
def show
@blogger = blogger.find(params[:id])
@title = @blogger.name
@posts = @blogger.posts
respond_with(@posts)
end
end
View
Index.html.erb
<% @blogger.post.each do |post| %>
post.name
# Comments to the Post
post.comments.each do |comment|
comment.comments
<% end %>
Model
class Post < ActiveRecord::Base
validates :name, :presence=>true
validates :title, :presence=>true
has_many :comments
belongs_to :blogger
belongs_to :topic, :touch => true
accepts_nested_attributes_for :blogger
attr_accessible :name, :title, :content
end
I ma getting a "NoMethodError in Posts#index" error which says
undefined method `post' for nil:NilClass and has the code for index.htm.erb in the extracted source
Upvotes: 1
Views: 3048
Reputation: 2280
not the answer, but just a few guidelines:
there are a lot of errors in your questions code.
@blogger = blogger.find(params[:id])
i think it should be changed to
@blogger = Blogger.find(params[:id])
at next make a
raise @blogger.inspect
and see if its loaded.
and in your view you can do better this: (btw: it needs to be called show.html.erb not index.html.erb if you have the show method)
#show html.erb
<%=render @blogger.posts %>
and then you make a file in posts/_post.html.erb
<%= post.name %>
<%= render post.comments %>
and a file comments/_comment.html.erb
where you render the comment.
this is rails way to be DRY!
Upvotes: 2
Reputation: 50057
The error you are looking for is a simple typo, in your view you should write
@blogger.posts.each
instead of
@blogger.post.each
Hope this helps.
Upvotes: 0
Reputation: 4855
Maybe because you put this code in index.html.erb So, when you try to display this HTML page, rails will try to call the method index in the controller, but you don't have any method called index. Try to put this code in a method called index / or try to change the name of your html.erb file to show.html.erb
EDIT : So, in your code you pass the @posts variable but in your view you called @blogger.post. It is not supposed to be resolved. You have to choose between passing @blogger or @posts to your view, and only use attributes of the variable you passed to the view.
Upvotes: 0