头像不显示给用户

Avatar is not showing for users

我正在使用 devise 作为我的用户身份验证和 carrierwave gem 用于图像上传。现在一切正常,头像被保存在用户 table 中并显示在索引视图中;但不在显示视图内。

为了让我的问题更清楚一点:

在索引视图中,头像已成功显示。

在show view里面,因为@user.avatarblank/nil

,头像会掉到默认图片

显示代码:

  <div class="well">
      <div class="media">
        <a class="pull-left">
        <% if @user.avatar.blank? %>
            <img src="http://www.adtechnology.co.uk/images/UGM-default-user.png" style="width: 75px;">
        <% elsif @user.avatar %>
            <%= image_tag @user.avatar, :style => "width:75px;" %>
        <% end %>
        </a>
        <div class="media-body">
          <p>About <%= link_to @question.user.username, @question.user, :class => " bg" %></p>
       </div>
       <p class="text-muted small">Apparently this user doesn't like to share his information.</p>
    </div>
  </div>

问题控制器:

class QuestionsController < ApplicationController
  before_action :set_question, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @questions = Question.all
    respond_with(@questions)
  end

  def show
    @user = User.find(params[:id])
    respond_with(@question)
  end

  def new
    if user_signed_in? 
      @question = current_user.questions.build
      respond_with(@question)
    else
      redirect_to new_user_session_path
    end
  end

  def edit
  end

  def create
    @question = current_user.questions.build(question_params)
    @question.save
    respond_with(@question)
  end

  def update
    @question.update(question_params)
    respond_with(@question)
  end

  def destroy
    @question.destroy
    respond_with(@question)
  end

  private
    def set_question
      @question = Question.find(params[:id])
    end

    def question_params
      params.require(:question).permit(:title, :description)
    end
end

用户模型:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  has_many :questions, :dependent => :destroy


  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

问题模型:

class Question < ActiveRecord::Base
    belongs_to :user
end

我通过更改 show.html.erb 中的这些行来修复它:

<% if @question.user.avatar.blank? %>
    <img src="http://www.adtechnology.co.uk/images/UGM-default-user.png" style="width: 75px;">
<% elsif @question.user.avatar %>
    <%= image_tag @question.user.avatar, :style => "width:75px;" %>
<% end %>
def show
    @user = User.find(params[:id])
    respond_with(@question)
end

由于在 QuestionsController 中调用了 show 操作,因此 params[:id] 将成为 @question 的 ID。您应该使用 @question.user 来引用 @question 的作者:

def show
    @user = @question.user
    respond_with(@question)
end