Reputation: 117
i am pretty new to rails and i want to set profile image of the user if he didnt provide one and to save it to database user controller create action
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
end
schema of user
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"
end
thanks in advance :)
Upvotes: 0
Views: 1223
Reputation: 42909
This will set the new value only if the old value is blank
@user = User.new(user_params)
@user.profilePicture ||= "/assets/images/default_image.jpg"
If profilePicture
could be an empty string then we might treat it like this
@user.profilePicture = "/assets/images/default_image.jpg" if @user.profilePicture.empty?
Upvotes: 2