【发布时间】:2017-04-04 10:18:41
【问题描述】:
在我的 rails 应用程序中,我希望有两种更新用户配置文件的补丁方法。
首先,我将有一个“account_settings”GET 请求,它将使用标准的编辑/更新 REST 操作来更新某些参数。然后,我想要一个额外的“edit_profile”和“update_profile”操作来获得一个允许用户更新不同用户属性的页面。这是我的users_controller.rb 中的外观,以获得更好的想法:
#For account settings page
#This is for the account settings page
#(only changing email and password)
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(account_settings_params)
flash.now[:success] = "Your settings have been successfully updated."
format.html {redirect_to @user}
else
format.html {redirect_to edit_user_path}
flash[:error] = "Please be sure to fill out your email, password, and password confirmation."
end
end
end
def edit_profile
@user = User.find(params[:id])
end
#For update profile
def update_profile
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(user_profile_params)
flash.now[:success] = "Your profile has been updated."
format.html {redirect_to @user}
else
format.html {redirect_to edit_profile_user_path}
flash[:error] = "Please be sure to fill out all the required profile form fields."
end
end
end
private
def account_settings_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
def user_profile_params
params.require(:user).permit(:name, :about_me, :location, :image_url)
end
从我当前的 routes.rb 中选择:
#Account Settings Just for Email and Password
get 'account_settings' => 'users#edit'
patch 'settings' => 'users#update'
resources :users do
member do
get :edit_profile
put :update_profile
end
end
rake 路由的结果:
edit_profile_user GET /users/:id/edit_profile(.:format) users#edit_profile
update_profile_user PATCH /users/:id/update_profile(.:format) users#update_profile
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
我的导航栏部分:
-if logged_in?
-# Logged in links
%li
=link_to 'Logout', logout_path, method: :delete
%li
=link_to 'Account Settings',edit_user_path(@current_user)
%li
=link_to 'Edit My Profile', edit_profile_user_path(@current_user)
%li
=link_to 'View My Profile', user_path(@current_user)
%li
=link_to 'Members', users_path
在 edit_profile 页面上,我的表单如下所示:
=form_for @user, path: update_profile_user_path(@user) do |f|
在我当前的实现中,访问 edit_profile 页面并发布表单将返回到常规编辑页面,我的 rails 服务器说参数是不允许的。但是,正如您在我的控制器中的 update_profile 方法中看到的那样,update_profile 的控制器方法接受 user_profile_params 而不是 account_settings_params 。关于它为什么会这样做的任何见解?
【问题讨论】:
-
在用户路由中使用
member或collection块
标签: ruby-on-rails ruby rest routing crud