简体   繁体   中英

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)

You should be getting an Undefined method 'content' for nil:NilClass error. The problem is that @micropost is not defined in the controller method (action) and so is nil .

And you can't call the content method on a nil object since it doesn't respond to it. In other words, there is no instance method named content defined on NilClass .

To fix the error, define an instance variable @micropost in the show action of UsersController .

# users_controller.rb

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

@user.microposts.first returns user's first post.

If the user has no posts associated with them, @user.microposts.first will return nil . So, you have to check if @micropost is nil before displaying it in the view.

# users/show.html.erb

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

I think you might be able to just do this in the users/show.html.erb:

@user.microposts.first.content

While not elegant, it's the simplest and satisfies the "edit the user show page" requirement of the exercise.

I also added @user.id because without it you don't know which user to add the microposts to for testing. Then you need to test to see if there is a microposts in order not break the code trying to display nil.

<p>
  <strong>ID:</strong>
  <%= @user.id %>
</p>


<% if @user.microposts.first %>
<p>
  <strong>First Post:</strong>
  <%= @user.microposts.first.content %>
</p>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM