It's a very strange bug bugged me for couple of hours already.
There are 3 models: user, school, post. Basically on the school page(school#show), there are a list of posts, and user can make new post.
The school controller:
def show
@school = School.find(params[:id])
$current_school = @school
@post = @school.posts.build if logged_in?
@posts = @school.posts
The school/show.html.erb:
<div>
<aside>
<%= render 'shared/post_form' %>
</aside>
</div>
<div>
<% if @school.posts.any? %>
<%= render @posts %>
<% end %>
</div>
_post_form.html.erb:
<%= form_for(@post) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Compose new post..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
posts/_post.html.erb:
<li>
<%= image_tag post.user.avatar.url(:thumb) %>
<span class="user"><%= link_to post.user.name, post.user %></span>
<span class="content"><%= post.content %></span>
</li>
Post controller:
def create
@post = $current_school.posts.create(content:params[:post[:content],user_id:current_user.id)
if @post.save
flash[:success] = "Post created!"
redirect_to $current_school
else
render 'static_pages/home'
end
end
The problem is, when navigate to school#show, it says
undefined method `avatar' for nil:NilClass
If I delete the
@post = @school.posts.build if logged_in?
line, and the _post_form.html.erb fragment, the list of posts shows fine. If I delete the _post.html.erb fragment, the new post function works fine as well.
But when they exist together, error comes up.
I guess the problem is at this line:
@post = @school.posts.build if logged_in?
because when I comment it out, the list of post shows fine. When I add it back, @posts can return a list of valid post, but post is nil.
Couldn't figure out what's wrong, please help.
Thanks
Edit: when visit url/schools/1, it crashes with NilClass error, post command returns
#<Post id: nil, content: nil, user_id: nil, school_id: 1, created_at: nil, updated_at: nil>
However, it should return the first post from @posts
Is it possible that
@post = @school.posts.build if logged_in?
assign @post a nil post, and when it renders @posts, it is looking for @post which become nil instead of first post in @posts? If so, how can I correct this?
Edit2: I tried to change @post to @test:
@test = @school.posts.build if logged_in?
and the same nilClass error persists. So my previous guess is not valid. There should be something wrong with using build here. But what's wrong?