“头像”未向用户显示

时间:2016-02-21 11:04:15

标签: ruby-on-rails devise carrierwave

我使用devise作为我的用户身份验证和carrierwave gem进行图片上传。现在一切运行良好,头像保存在用户表中,并显示在索引视图中;但不在展会视图内。

让我的问题更加明确:

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

enter image description here

在展示视图中,头像属于默认图片,因为blank/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>

enter image description here

显示代码:

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

问题模型:

EJSON.clone()

2 个答案:

答案 0 :(得分:1)

我通过更改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 %>

答案 1 :(得分:1)

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