Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用保存到数据库的rails创建联系人表单_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如何使用保存到数据库的rails创建联系人表单

Ruby on rails 如何使用保存到数据库的rails创建联系人表单,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试创建一个联系我们样式的表单,将信息保存到数据库中,并向管理员地址发送电子邮件。我一直在研究如何在rails中实现这一点,以便将数据保存到数据库中。我还想实施验证并使用tdd。模型 您需要考虑以下几点: #config/routes.rb resources :contact, only: [:new, :create], path_names: { new: "" } #app/models/contact.rb Class Contact < ActiveRecord::Ba

我正在尝试创建一个联系我们样式的表单,将信息保存到数据库中,并向管理员地址发送电子邮件。我一直在研究如何在rails中实现这一点,以便将数据保存到数据库中。我还想实施验证并使用tdd。

模型

您需要考虑以下几点:

#config/routes.rb
resources :contact, only: [:new, :create], path_names: { new: "" }

#app/models/contact.rb
Class Contact < ActiveRecord::Base
   validates :name, :email, :message, presence: { message: "You need to fill all the fields!" }
end

#app/controllers/contact_controller.rb
Class ContactController < ApplicationController
    def new 
       @contact = Contact.new
    end

    def create
       @contact = Contact.new(contact_params)
       @contact.save
    end
end

#app/views/contact/new.html.erb
<%= form_for @contact do |c| %>
    <%= c.text_field :name %>
    <%= c.text_field :email %>
    <%= c.text_field :message %>
    <%= c.submit %>
<% end %>
要确定如何发送电子邮件,您需要

#app/models/contact.rb
Class Contact < ActiveRecord::Base
   after_create :send_email

   private

   def send_email
      ... email code here
   end
end