表单中的第一个参数不能包含nil或者是空的rails 4

时间:2013-10-30 19:20:53

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

我有以下表格

<%= form_for @contact, url: new_contact_path(@contact), remote: true do |f| %>
<%= f.text_field :name %>
<%= f.text_field :email %>
<%= f.text_field :phone %>
<%= f.text_field :message %>
<%= f.submit 'Send' %>

这是我的控制器contacts_controller.rb

def new
        @contact = Contact.new
    end

    def create
        unless contact_params.nil?
            @contact = Contact.new contact_params
            @contact.save
        end
    end

当我提交表单时收到错误

First argument in form cannot contain nil or be empty

我也试过这个

<%= form_for Contact.new, url: {controller: :contact,action: :create}, remote: true do |f| %>

但是收到路由错误

这是我的rake routes

contacts GET      /contacts(.:format)                    contacts#index
                   POST     /contacts(.:format)                    contacts#create
       new_contact GET      /contacts/new(.:format)                contacts#new
      edit_contact GET      /contacts/:id/edit(.:format)           contacts#edit
           contact GET      /contacts/:id(.:format)                contacts#show
                   PATCH    /contacts/:id(.:format)                contacts#update
                   PUT      /contacts/:id(.:format)                contacts#update
                   DELETE   /contacts/:id(.:format)                contacts#destroy

我的route.rb有

resources :contacts

更新-1

private
    def contact_params
        params.require(:contact).permit(:customer_id,:post_id,:name,:email,:phone,:message)
    end

1 个答案:

答案 0 :(得分:0)

您最有可能收到错误,因为您的视图中未定义@contact。我不确定您在哪个视图中拥有该表单,或者您是否正在呈现该表单,但请在@contact声明之前尝试声明unless

def create
  @contact = Contact.new contact_params

  unless contact_params.nil?        
    @contact.save
  end
end

或类似的东西......无论哪种方式,你必须在控制器动作中定义@contact,与包含你的表单的视图相对应,如果这是有道理的。