【问题标题】:Rails create a model from form that isn't stored in a databaseRails 从未存储在数据库中的表单创建模型
【发布时间】:2015-01-27 16:35:21
【问题描述】:

我有一个我想从注册控制器和表单创建的帐户模型。

index.html.erb

<div id="registration">
<%= form_for(@account) do |f| %>
<% if @account.errors.any? %>

register_controller.rb

class RegisterController < ApplicationController
  def index 
    @account = Account.new
  end

  def create
    @account = Account.new(parames[:account])
  end
end
  end

end

routes.rb

Rails.application.routes.draw do
  get 'register/index'
  get 'register/create'

我当前的问题是来自 form_for() 方法的 # 的未定义方法 `accounts_path'

我是不是因为类名而把事情搞混了?

【问题讨论】:

  • 默认情况下,form_for 将尝试“猜测”提交表单的 URL。在你的情况下,你不希望表单提交给accounts_path,而是提交给form_for @account, url: registers_path(如果你在你的routes.rb中定义resources :register,否则我需要查看你的路由配置)

标签: ruby-on-rails ruby model controller


【解决方案1】:

form_for(@account) 会自动设置表单的一些属性,比如“action”,就是表单提交的地方。如果您想将其更改为其他内容,请使用 url 选项。您可以将其传递给路径帮助程序,也可以将 url 放入其中。例如

<!-- if you have a named path you can use the helper for it -->
<%= form_for @article, url: create_register_path %>

<!-- alternatively just pass the url -->
<%= form_for @article, url: "/register/create" %>

<!-- or you can pass the url as a hash if you prefer -->  
<%= form_for @article, url: {controller: "register", action: "create"} %>

http://guides.rubyonrails.org/form_helpers.html

编辑:我刚刚在您对帖子的编辑中注意到“注册/创建”设置为get 路由。这意味着您还需要告诉表单使用get 方法:默认为post

<%= form_for @article, url: "/register/create", :method => :get %>

【讨论】:

  • 顺便说一句,让您的 url/控制器与您的对象类名称相匹配通常是一个好习惯 - 它会为您节省一些混乱,并且您必须减少对默认值的覆盖。
猜你喜欢
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多