Ruby on Rails教程Michael Hart - 未在用户索引视图上显示的用户(第9章)

时间:2013-11-14 00:57:19

标签: ruby-on-rails ruby railstutorial.org

章: 9.2页405
问题:没有显示任何用户名或头像。

enter image description here

用户/索引

<% provide(:title, 'All users') %>
<h1>All users</h1>

<ul class="users">
  <% @users.each do |user| %>
    <li>
      <% gravatar_for user, size: 52 %>
      <% link_to user.name, user %>
    </li>
  <% end %>
</ul>

UsersController

class UsersController < ApplicationController
  before_filter :signed_in_user, only: [:index, :edit, :update]
  before_filter :correct_user,   only: [:edit, :update]
  def show
    @user = User.find(params[:id])
  end  

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      # Handle a successful save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def index
    @users = User.all
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    if @user.user_attributes(params[:users])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

  private

  def signed_in_user
    redirect_to signin_path, notice: "Please sign in." unless signed_in?
  end

  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user)
  end
end

sample_data.rake

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    User.create!(name: "Example User",
                 email: "example@railstutorial.org",
                 password: "foobar",
                 password_confirmation: "foobar")
    99.times do |n|
      name = Faker::Name.name
      email = "example-#{n+1}@railstutorial.org"
      password = "password"
      User.create!(name: name,
                   email: email,
                   password: password,
                   password_confirmation: password)
    end
  end
end

如果我遗漏了您需要查看的任何代码,如果我的问题中存在任何误解,请告诉我。感谢您的帮助和时间。

2 个答案:

答案 0 :(得分:2)

您实际上并没有在视图中打印出内容。

<%会评估内容但不会打印出来; <%=会对其进行评估并打印出来。

所以你需要修改这两行:

<% gravatar_for user, size: 52 %>
<% link_to user.name, user %>

添加缺少的=

答案 1 :(得分:0)

使用%=以HTML格式显示:

<li>
  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
</li>