首页 > 解决方案 > 将自定义表单添加到设计编辑页面 Ruby on Rails

问题描述

我在将自定义表单添加到设计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

现在我想添加从设计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)。我究竟做错了什么?甚至可以将自定义表单添加到设计中吗?非常感谢您的帮助和时间。

更新:

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

标签: ruby-on-railsrubydevise

解决方案


在这里,您的路由用户/编辑/地址是从匹配中生成的,并且是通过 get 方法编写的,因此您需要使用

match 'user/edit/addresses' => 'registrations#addresses', via: :post, :as => :user_addresses

并且在表单 url path helper 中,您将当前用户作为参数传递,而它在您的路由中不存在,因此表单应该替换为

= form_for user_addresses_path, url: user_addresses_path, method: 'post', :html => { class: "form", :multipart => true } do |f|

推荐阅读