我有一個表格供人們捐贈。它需要電子郵件和名稱。我還沒有添加條紋..只是試圖讓表格首先工作,並將他們的電子郵件/名稱保存到數據庫。模型驗證導致錯誤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>
讓我知道你是否需要別的東西。感謝你們。
@Kathan也不需要'attr_accessor:name,:email'。 –
感謝您的快速回復。當我使用'資源:捐款'而不是手動定義路線時,我得到這個錯誤:'找不到'DonationsController'的動作索引'但是,我改變了一切,它的工作原理:D – Kathan
@AndreyTurkin編輯,thx –