Romas Ran Romas Ran - 3 months ago 159
Ruby Question

Ruby on Rails Tutorial (Michael Hartl) Chapter 2 Exercise 2.3.3.1 "Edit the user show page to display the content of the user’s first micropost."

Full descriptions of task sounds:
Edit the user show page to display the content of the user’s first micropost. (Use your technical sophistication (Box 1.1) to guess the syntax based on the other content in the file.) Confirm by visiting /users/1 that it worked.

My first idea was to update app/views/users/show.html.erb into

<p id="notice"><%= notice %></p>

<p>
<strong>Name:</strong>
<%= @user.name %>
</p>

<p>
<strong>Email:</strong>
<%= @user.email %>
</p>

<p>
<strong>Content:</strong>
<%= @micropost.content %>
</p>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>


But seems I haven't got idea behind task? Any suggestions from what I should start from?
Biggest thanks for your responses)

Answer

You should be getting an error which reads Undefined method content for nil:NilClass. The problem is that @micropost is not defined in the controller action and so is nil. You can't call a method on a nil object.

Define an instance variable @micropost in the show action of UsersController.

# users_controller.rb

def show
  # find the user record
  @user = User.find(params[:id])
  @micropost = @user.microposts.first
end

@user.microposts grabs all the user's posts and the first method gets the first post.

What if the user has no microposts associated with him ? @user.microposts.first will return nil. So, you have to additionally check if @micropost is nil before displaying it in the view.

Otherwise you'll get an error which reads Undefined method content for nil:Nilclass cause you can't call the content method on nil.

users/show.html.erb

<% if @micropost %> 
  <p>
    <strong>Content:</strong>
    <%= @micropost.content %>
  </p>
<% end %>

Hope this helps!