2023-08-24 10:20AM
1. 在管理员用户表中增加avatar_path列
bundle exec rails generate migration add_avatar_path_to_users
在生成文件中增加下面的代码:
add_column :users, :avatar_path, :string, comment: '头像路径'
2. 在config/routes里面增加路由
resources :users do
collection do
get :show_profile
get :edit_profile
post :save_profile
end
end
3. 在app/controllers/users_controller.rb里面增加下面的代码:
def show_profile
if session[:current_user].blank?
redirect_to '/articles' and return
end
@user = User.find session[:current_user]['id']
end
def edit_profile
if session[:current_user].blank?
redirect_to '/articles' and return
end
end
def save_profile
if session[:current_user].blank?
redirect_to '/articles' and return
end
uploaded_io = params[:avatar_image]
file_name = Rails.root.join('public', 'images', uploaded_io.original_filename)
File.open(file_name, 'wb') do |file|
file.write(uploaded_io.read)
end
user = User.find session[:current_user]['id']
user.avatar_path = '/images/' + uploaded_io.original_filename
user.save!
redirect_to '/users/show_profile'
end
4. 然后增加 app/views/users/show_profile.html.erb 文件
<h1>个人档案</h1>
<p>我的头像
<%= link_to '编辑', 'edit_profile', style: 'margin-left: 20px; text-decoration: none;' %>
</p>
<%= @user.avatar_path %><br/>
<img src="<%= @user.avatar_path %>", style='width: 200px; height: 200px; margin-top: 20px;' />
5. 然后增加 app/views/users/edit_profile.html.erb 文件
<h1>编辑个人档案页面</h1>
<p>我的头像
<%= link_to '返回', show_profile_users_path, style: 'margin-left: 20px; text-decoration: none;'%>
</p>
<%= form_tag '/users/save_profile', multipart: true do %>
<%= file_field_tag "avatar_image" %>
<%= submit_tag "提交" %>
<% end %>
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论