将自定义表单添加到Devise编辑页面Ruby on Rails中

时间:2019-06-18 14:53:44

标签: ruby-on-rails ruby devise

我在将自定义表单添加到Devise edit页面时遇到问题。目前,我有两个模型UserUserAddress。我在多页上拆分了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控制器来处理createdestroy动作:

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

1 个答案:

答案 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|