发送通知并将信息保存到数据库

时间:2011-06-23 13:14:09

标签: forms ruby-on-rails-3

我有一个表单,在客户填写表单时发出通知。我知道希望能够将这些信息保存在我的数据库表中,但是我遇到了问题。除非我清除我的模型,否则它根本不会将副本保存到数据库中。这是控制器和模型的样子。

class ContactController < ApplicationController

  def index
    @contact = Contact.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @contact }
    end
  end

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

    if verify_recaptcha(request.remote_ip, params)[:status] == 'false'
      render 'index', :layout => '/layouts/application.html.erb'
  elsif
    respond_to do |format|
      if @contact.save
        format.html { redirect_to("/contact", :notice => 'Your Message was successfully sent.') }
      else
        format.html { render :action => "index" }
        format.xml  { render :xml => @contact.errors, :status => :unprocessable_entity }
      end
    end
  end
end

end

模型

class Contact < ActiveRecord::Base

  include ActiveModel::Validations

  validates_presence_of :email, :phone, :phone_type, :address, :fullName, :content, :userBrowser, :userOS

  attr_accessor :id, :email, :phone, :phone_type, :address, :fullName, :content, :userBrowser, :userOS

  def initialize(attributes = {})
    attributes.each do |key, value|
      self.send("#{key}=", value)
    end
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end

  def to_key
  end

  def save
    if self.valid?
      Notifier.contact_notification(self).deliver
      return true
    end
    return false
  end
end

所有帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

我不确定为什么你压倒这么多的父方法,所有你需要使通知器工作的是

class Contact < ActiveRecord::Base
  validates_presence_of :email, :phone, :phone_type, :address, :fullName, :content, :userBrowser, :userOS

  after_save :send_contact_notification

  def send_contact_notification
    Notifier.contact_notification(self).deliver
  end
end

此外,您不必包含Validations,它们已经可用,如果您尝试保护模型字段,您可能需要attr_accessible而不是attr_accessor,因为后者已由ActiveRecord处理。