Ruby on Rails 在多个页面上使用相同的表单时出错

Ruby on Rails error when using same form on multiple pages

我有一个联系表单设置并在我的 'Contact' 页面上工作。但是,当我将该表单复制到另一页时,出现此错误:'First argument in form cannot contain nil or be empty'.

这是我的联系人控制器:

class ContactsController < ApplicationController

  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])

    if @contact.valid?
      ContactMailer.contact_email(@contact).deliver_now
      redirect_to new_contact_path, notice: "Your email has been sent. Thank you."
    else
      render :new
    end
  end

end

这是另一个页面控制器:

class GolfcoursesController < ApplicationController
  protect_from_forgery

  def index
    @golf_courses = GolfCourse.all
  end

  def show
    @golf_courses = GolfCourse.all
    @golfcourse = GolfCourse.find_by(slug: params[:slug])
    @holes = @golfcourse.golf_holes
  end

  def events
  end

  def membership
  end

  def practice_facilities
  end

  def contact
  end

  def golf
    @golf_courses = GolfCourse.all
  end

  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])

    if @contact.valid?
      ContactMailer.contact_email(@contact).deliver_now
      redirect_to new_contact_path, notice: "Your email has been sent. Thank you."
    else
      render :new
    end
  end
end

这是表格:

<div class="container">
    <h4>Let us know if you have any questions.</h4>
    <%= form_for @contact, :html => {:role => 'form'} do |f| %>
        <div class="form-group">
          <%= f.label :name, 'Enter your name:' %>
          <%= f.text_field :name, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :email, 'Email:' %>
          <%= f.email_field :email, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :message, 'Message:' %>
          <%= f.text_area :message, class: 'form-control', :rows => 3 %>
        </div>

        <div class="form-group">
          <%= f.submit 'Submit', class: 'btn btn-default' %>
        </div>

    <% end %>
</div>

在此先感谢您的帮助!

'First argument in form cannot contain nil or be empty'

您还应该在其他控制器中初始化 @contact

如果您想共享表单,我建议使用局部变量并传入局部变量。这使您的代码也有些枯燥。

另请参阅 rails 指南作为参考: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials