Rails - 从控制器为用户设置默认图片?

时间:2015-02-27 12:46:08

标签: ruby-on-rails

我对rails很新,我想设置用户的个人资料图片,如果他没有提供并将其保存到数据库 用户控制器创建动作

  def create
@user = User.new(user_params)
@user.profilePicture
if(@user.profilePicture.length==0)
  profilePicture="/assets/images/default_image.jpg" # problem is here
end
respond_to do |format|
  if @user.save
    session[:user_id] = @user.id
    format.html { redirect_to @user }
    format.json { render :show, status: :created, location: @user }
  end
end

用户架构

create_table "users", force: :cascade do |t|
t.string   "fisrt_name"
t.string   "email"
t.string   "password"
t.datetime "created_at",     null: false
t.datetime "updated_at",     null: false
t.string   "profilePicture"

提前感谢:)

1 个答案:

答案 0 :(得分:2)

仅当旧值为空时才会设置新值

@user = User.new(user_params)
@user.profilePicture ||= "/assets/images/default_image.jpg"

如果profilePicture可能是一个空字符串,那么我们可能会像这样对待

@user.profilePicture = "/assets/images/default_image.jpg" if @user.profilePicture.empty?