2011-06-23 107 views
0

我有一個窗體在客戶填寫表單時發出通知。我知道希望能夠將此信息保存在我的數據庫表中,但遇到問題。除非我清除我的模型,否則它不會將副本保存到數據庫中。這裏是控制器和模型的外觀。發送通知並將信息保存到數據庫

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

我不知道爲什麼你的首要這麼多的父方法,所有你應該需要做的通知工作

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 

而且你不應該包括驗證,他們是已經可用了,如果你試圖保護模型字段,你可能需要attr_accessible而不是attr_accessor,因爲後者已經被ActiveRecord處理了。

+0

我原本是在線學習了一個只有電子郵件發送數據的教程,它沒有存儲它,在rails中是新的,我仍然試圖弄清楚它是如何工作的。 – mediarts

相關問題