2015-04-17 23 views
0

我有一個表格供人們捐贈。它需要電子郵件和名稱。我還沒有添加條紋..只是試圖讓表格首先工作,並將他們的電子郵件/名稱保存到數據庫。模型驗證導致錯誤Rails 4

當我向我的模型添加一個存在驗證時,它不會接受任何東西。它只是返回f.error通知。當我擺脫驗證時,表單提交成功,但沒有任何內容保存到數據庫中。 rails控制檯只返回名稱和電子郵件的無名稱。

還是新的鐵軌,所以可能是簡單的事情。任何建議都會很棒。

donation.rb(模型):

class Donation < ActiveRecord::Base 
    attr_accessor :name, :email 

    validates :name, 
    presence: true 

    validates :email, 
    presence: true 
end 

donations_controller:

class DonationsController < ApplicationController 
    def new 
    @donation = Donation.new 
    end 

    def create 
    @donation = Donation.new(params[donation_params]) 
    if @donation.valid? 
     redirect_to root_path, notice: "Thank you. We have received your donation." 
    else 
     flash[:alert] = "An error occurred, please try again." 
     render :new 
    end 
    end 

private 

    def donation_params 
    params.require(:donation).permit(:name, :email) 
    end 
end 

routes.rb中:

get 'donations', to: 'donations#new', as: 'donations' 
post 'donations', to: 'donations#create' 

new.html.erb(捐贈視圖):

<body class ="CU"> 
    <div class="authform"> 
    <%= simple_form_for @donation, :url => donations_path do |f| %> 
    <h1 style = "text-align:center; color:black;">Donate</h1> 
    <%= f.error_notification %> 
    <div class="form-group"> 
     <%= f.text_field :name, placeholder: 'Name', :autofocus => true, class: 'form-control' %> 
    </div> 
    <div class="form-group"> 
     <%= f.text_field :email, placeholder: 'Email', class: 'form-control' %> 
    </div> 
    <%= f.submit 'Donate', :class => 'btn btn-lg btn-danger btn-block' %> 
    <% end %> 
    </div> 
</body> 

讓我知道你是否需要別的東西。感謝你們。

回答

3

這部分嘗試這種if @donation.save代替if @donation.valid?

@donation = Donation.new(params[donation_params]) 

實際上應該是:

@donation = Donation.new(donation_params) 

而且你創建的方法不保存記錄。使用save而不是valid?

此外,爲什麼你把breakline放在你的驗證定義中?

此外,使用的RESTful路線,即:

resources :donations 

,而不是手動定義每個路由。

此外,由於您使用strong params,你不需要attr_accessor(它應該是attr_accessible它的情況下,但無論如何)。 您將使用attr_accessor來定義虛擬屬性,但我確定情況並非如此,因爲nameemail是數據庫支持的字段。

最後,只要走過Rails guides - 你會發現所有需要的信息。

+0

@Kathan也不需要'attr_accessor:name,:email'。 –

+0

感謝您的快速回復。當我使用'資源:捐款'而不是手動定義路線時,我得到這個錯誤:'找不到'DonationsController'的動作索引'但是,我改變了一切,它的工作原理:D – Kathan

+0

@AndreyTurkin編輯,thx –

0

因爲你不保存,在create