Rails 5中使用带命名空间与as属性的form_for报错求助
解决Rails 5中form_for结合命名空间与as别名的路径报错问题
你的报错undefined method 'customer_user_path'本质是Rails自动生成路径时出现了偏差——你用[:customer, current_user]作为form_for的参数,Rails会根据current_user的模型(比如User)尝试生成customer_user_path,但你的路由实际定义的是customer_profile_path这类单数profile路径,所以出现了方法未定义的错误。
下面给出两种可靠的解决方案:
方案一:直接指定表单提交URL(推荐)
既然你的更新路由是customer_profile_path,直接在form_for里明确指定url选项,同时保留as: :profile来确保参数被包裹在params[:profile]中:
<%= form_for current_user, as: :profile, url: customer_profile_path, method: :patch do |f| %> <!-- 表单字段 --> <% end %>
method: :patch对应你路由里的PATCH/PUT请求方式;as: :profile会让表单参数以params[:profile]的形式传递到控制器,和你路由的as别名一致。
方案二:调整form_for的资源标识
如果你更倾向于使用命名空间+资源的数组写法,可以把:profile作为资源标识结合命名空间,同时指定模型为current_user:
<%= form_for [:customer, :profile], model: current_user, as: :profile do |f| %> <!-- 表单字段 --> <% end %>
这种写法会让Rails正确识别到要使用customer_profile_path,同时绑定current_user作为表单的数据源。
控制器参数处理提示
别忘了在Customer::ProfilesController里,按照as: :profile的约定来接收参数:
class Customer::ProfilesController < ApplicationController before_action :authenticate_user! def edit @user = current_user end def update @user = current_user if @user.update(profile_params) redirect_to customer_profile_path, notice: 'Profile updated successfully!' else render :edit end end private def profile_params params.require(:profile).permit(:name, :email, :phone) # 替换成你的实际字段 end end
内容的提问来源于stack exchange,提问作者Javier Valencia
相关产品推荐
相关产品推荐

