【问题标题】:Contact Me Form for One Page Layout一页布局的联系我表格
【发布时间】:2015-08-18 16:15:17
【问题描述】:

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

#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' %>

我收到的主要错误是First argument in form cannot contain nil or be empty。我也尝试将@contact = Contact.new 放在欢迎控制器的索引操作中,但这会引发这个问题:Unable to autoload constant Contact, expected .../app/mailers/contact.rb to define it

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

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

更新

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

【问题讨论】:

  • 表单代码属于哪个视图页面?
  • 表单代码在联系人视图文件夹下的一部分,然后将显示在索引视图上。
  • 那么在index 操作中使用@contact = Contact.new 是正确的。我猜另一个错误与邮件有关。
  • 有道理;但是,那个邮件问题让我陷入了困境。我知道这意味着什么。我还没有设置邮件程序。我不认为我还必须这样做?
  • 尝试将resources :contact, only: [:new, :create]更改为resources :contacts, only: [:new, :create]

标签: ruby-on-rails ruby forms ruby-on-rails-4


【解决方案1】:

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

如果您转到 /routes,您会看到您只创建 :create 路由,因为资源 :contact 文件中的“only: [:create]”语句。

这可能看起来违反直觉,但您也需要 :new 路线,因为这会呈现您在控制器中拥有的新视图。基本上宁静的 Rails 路线是配对的:new 提交给 :create 和 :edit 提交给 :update。所以 :create 和 :update 没有视图,如果有问题,它们会渲染 :new 或 :edit 视图。

【讨论】:

  • 啊,是的,我认为那里应该有一个 :new,但不确定。我记得添加但仍然没有。现在我知道应该是,谢谢,我已添加,但仍然存在相同的邮件问题。也更新了代码。
【解决方案2】:

这可能不是您问题的答案,但在此框中发布代码比在 cmets 框中更容易。我看到了一些需要解决的问题

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

【讨论】:

  • 谢谢 =) 可能不是答案,但总是能收到输入。我很感激。
【解决方案3】:

感谢大家的意见,但我发现了我的错误。导致该问题的邮寄者名称存在问题。当我需要contact_mailer.rb时,我有contact.rb。

感谢大家的其他建议!

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多