模型验证导致错误 Rails 4

Model validations causing error Rails 4

我有一个供人们捐款的表格。它需要电子邮件和姓名。我还没有添加 stripe.. 只是想让表单先工作并将它们的 email/name 保存到数据库中。

当我向我的模型添加存在验证时,它不接受任何东西。它只是 returns f.error 通知。当我摆脱验证时,表单提交成功但没有任何内容保存到数据库中。 rails 控制台只是 returns 姓名和电子邮件为零。

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>

如果您还需要什么,请告诉我。谢谢你们。

因为你没有保存它,所以试试这个 if @donation.save 而不是 create

中的 if @donation.valid?

这部分

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

实际上应该是:

@donation = Donation.new(donation_params)

您的创建方法也没有保存记录。使用 save 而不是 valid?

另外,您为什么要在验证定义中加入分界线?

另外,使用RESTful路由,即:

resources :donations

而不是手动定义每条路线。

此外,由于您使用 strong params,因此不需要 attr_accessor(在 rails 的情况下应该是 attr_accessible,但无论如何)。 您会使用 attr_accessor 来定义虚拟属性,但我确信情况并非如此,因为 nameemail 是数据库支持的字段。

最后,只需浏览 Rails guides - 您会找到所有需要的信息。