gpt4 book ai didi

ruby-on-rails - 一页布局的联系我表格

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:10 25 4
gpt4 key购买 nike

我正在用单页布局创建“联系我”表单。我已经设置了大部分代码,但似乎无法解决出现的错误。我将把所有带有错误的代码放在下面。注意:我还没有设置邮件程序,一旦正确设置了这段代码,我就打算这样做:)

#routes
Rails.application.routes.draw do
resources :contacts, only: [:new, :create]
devise_for :users
root 'welcome#index'
end

#form
<%= form_for @contact do |x| %>
<div class="field">
<%= x.label :name %><br />
<%= x.text_field :name %>
<%= x.submit %>
</div>
<% end %>

#ContactsController
class ContactsController < ApplicationController
def new
@contact = Contact.new
end

def create
@contact = Contact.new(contact_params)
if @contact.save
flash[:notice] = "Your message has been sent!"
redirect_to :action => :index
else
flash[:notice] = "Try Again!"
end
end

private
def contact_params
params.require(:contact).permit(:name)
end
end

#Index View
<%= render partial: 'contacts/form' %>

我最常收到的错误是表单中的第一个参数不能包含 nil 或为空。我还尝试将 @contact = Contact.new 放在欢迎 Controller 的索引操作中,但这引发了这个问题:Unable to autoload constant Contact, expected .../app/mailers/contact.rb 来定义它

如果您有任何建议、想法或意见,请告诉我=)非常感谢任何帮助,谢谢!

PS:如果需要任何进一步的代码或信息,请询问。有一个包含各种列的联系人模型。

更新

我现在在欢迎 Controller 的索引操作中有 @contact = Contact.new。最终尝试解决我收到的邮件问题。

最佳答案

首先你的路线是错误的(顺便说一句,资源:联系线应该在文件的顶部),把它想象成从上到下的瀑布。

如果你去/routes,你会看到你只创建了 :create 路由,因为路由文件的 resources:contact 部分中有“only: [:create]”语句。

这似乎违反直觉,但您也需要 :new 路由,因为这会呈现您在 Controller 中拥有的新 View 。本质上,restful rails 路由是成对的:new 提交给 :create 和 :edit 提交给 :update。所以 :create 和 :update 没有 View ,如果有问题,它们会渲染 :new 或 :edit View 。

关于ruby-on-rails - 一页布局的联系我表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com