2016-08-30 80 views
0

如何使用沒有數據庫表格的模型(比如聯繫表單)驗證表單(因此不需要標準記錄驗證)。使用模型驗證表單

我試過這個,但是我得到錯誤: undefined method有效?'爲聯繫人:Class`

class Contact 
    include ActiveModel::Validations 
    attr_accessor :subject, :query 
    validates :subject, { :presence => { message:'Please select a subject' } } 
    validates :query, { :presence => { message:'Please enter your message' } } 
    def initialize(attributes = {}) 
    attributes.each do |name, value| 
     send("#{name}=", value) 
    end 
    end 
    def persisted? 
    false 
    end 
end 

然後方法:

def contact 
    @page_title = 'Contact Us' 
end 

def contact_email 
    if Contact.valid? 
    message = "#{params[:subject]}: #{params[:query]}" 
    current_user.send_contact_message(message) 
    redirect_to '/contact', notice: 'Thank you for your message, we will be in touch shortly.' 
    else 
    render :contact 
    end 
end 
+0

的可能的複製[Rails的4 - 驗證模型沒有數據庫(http://stackoverflow.com/questions/16865821/rails-4-validate- model-without-a-database) –

回答

1

valid?是一個實例方法。你只能在類的實例上而不是在類上調用它。你需要改變這一行

if Contact.valid? 

這個

contact = Contact.new(subject: 'some subject', query: 'some query') 
if contact.valid? 

希望幫助!

+0

試過了,現在我得到錯誤「未定義的方法」有效?對於#' – Cameron

+0

哎呀抱歉,不知道該方法是在控制器中,您需要在聯繫對象上調用它,檢查我的編輯。 – RSB

+1

完美!謝謝。 – Cameron

0

Rails 4的新功能之一是ActiveModel::Model,這使得創建無表模型非常容易。它給你驗證,通過I18n模塊翻譯,表單綁定,多態路由等。幾乎所有的ActiveRecord::Base除了持久性。

class Contact < ActiveModel::Model 
    attr_accessor :subject, :query 
    validates :subject, presence: { message:'Please select a subject' } 
    validates :query, presence: { message:'Please enter your message' } 
end 

除此之外你錯誤的事實,您呼叫.valid?的聯繫類,而不是一個實例造成的。

軌道的辦法是做:

# config/routes.rb 
resources :contacts, only: [:new, :create] 

# app/controllers/contacts_controller.rb 
class ContactsController < ApplicationController 

    def new 
    @contact = Contact.new 
    end 

    def create 
    @contact = Contact.new(contact_params) 
    if @contact.valid? 
     message = "#{params[:subject]}: #{params[:query]}" 
     current_user.send_contact_message(message) 
     redirect_to '/contact', notice: 'Thank you for your message, we will be in touch shortly.' 
    else 
     render :new 
    end 
    end 

    private 

    def contact_params 
     params.require(:contact).permit(:foo, :bar) 
    end 
end