我在将自定义表单添加到Devise edit
页面时遇到问题。目前,我有两个模型User
和UserAddress
。我在多页上拆分了edit
页,这是我的路线:
devise_for :users, path: "user", path_names: {sing_in: "sign_in", sing_out: "sign_out", sing_up: "sign_up", edit: "edit"}, :controllers => { :registrations => :registrations }
devise_scope :user do
match 'user/edit' => 'registrations#edit', via: :get, :as => :user_basic
match 'user/edit/addresses' => 'registrations#addresses', via: :get, :as => :user_addresses
...
resources :user_addresses, only: [:create, :destroy]
end
resources :users, path: "user", only: [:show]
我创建了User Addresses
控制器来处理create
和destroy
动作:
class UserAddressesController < ApplicationController
def create
@User = User.find(params[:user_id])
if params[:addresses]
params[:addresses].each do |address|
@User.address.create(address: address)
end
@addresses = @User.addresses
redirect_back(fallback_location: request.referer, notice: "Success")
end
end
def destoy
@address = Address.find(params[:id])
@User = @address.user
@address.destroy
@addresses = Address.where(user_id: @user.id)
respond_to :js
end
end
现在,我想添加从Devise edit
页添加新地址的功能(我最近将使用ajax
来更新表单下的记录),就像这样(haml
):
= form_for user_addresses_path, url: user_addresses_path(current_user), method: 'post', :html => { class: "form", :multipart => true } do |f|
= f.text_field :name
= f.text_field :address
= f.submit
单击submit
时,出现以下错误:
No route matches [POST] "/user/edit/addresses.1"
我认为我需要将resources :user_addresses, only: [:create, :destroy]
从devise_scope
中移出,但是我不想更改url
(www.url.com/user/edit/addresses )。我究竟做错了什么?甚至可以将自定义表单添加到Devise中吗?非常感谢您的帮助和时间。
更新:
UserAddress
模型:
class UserAddress < ApplicationRecord
belongs_to :user, :foreign_key => 'user_id'
# Geocoder
geocoded_by :address
after_validation :geocode, :if => lambda{ |obj| obj.address_changed? }
end
答案 0 :(得分:1)
在这里,您的路线用户/编辑/地址是从匹配中生成的,并通过get方法写入,因此您需要使用
进行更改match 'user/edit/addresses' => 'registrations#addresses', via: :post, :as => :user_addresses
,并且在表单url路径帮助器中,您正在传递当前用户作为参数,而路由中不存在该用户,因此表单应替换为
= form_for user_addresses_path, url: user_addresses_path, method: 'post', :html => { class: "form", :multipart => true } do |f|