Rails验证现有数据的错误

时间:2018-01-19 19:29:19

标签: ruby-on-rails activerecord model

我正在rails 5.1.4 上构建一个简单的费用管理应用程序。我使用以下五种型号。

收款人

class Payee < ApplicationRecord
  has_many :expenses
  validates :title, uniqueness: true, presence: true
end

帐户

class Account < ApplicationRecord
 before_save :update_balance
 validates :balance, numericality: { greater_than_or_equal_to: 0 }
 has_many :expenses
end

预算

class Budget < ApplicationRecord
 belongs_to :categories
 has_many :expenses, through: :categories
end

分类

class Category < ApplicationRecord
  validates :title, uniqueness: true, presence: true
  has_many :expenses
  has_one :budget
end

费用

class Expense < ApplicationRecord
  belongs_to :categories
  belongs_to :budgets
  belongs_to :payees
  belongs_to :accounts
  validates :title, :value, presence: true
  before_save :default_account
end

当我尝试创建新费用时,我面临验证错误

  

验证失败:类别必须存在,预算必须存在,Paye必须存在,帐户必须存在

问题是所有上述记录都存在。为了解释我的自我,我说我正在通过参数account_id: 1, payee_id: 1, category_id: 1。如果我这样做:

Account.find(1) #=> Finds the record
Category.find(1) #=> also ok
Payee.find(1) #=> also ok

我知道this question中引用的解决方案(添加optional: true)但我不知道为什么我应该这样做,而上述所有内容都存在

修改

引发错误的代码是:

def create
  @expense = Expense.create!(title: params[:expense]['title'],
                           value: params[:expense]['value'],
                           date: params[:expense]['date'],
                           comment: params[:expense]['comment'],
                           payee_id: params[:expense]['payee_id'],
                           category_id: params[:expense]['category_id'],
                           account_id: params[:expense]['account_id'])
end

通过表单传递的参数是

  

{&#34; UTF8&#34; = GT;&#34;✓&#34 ;,    &#34; authenticity_token&#34; = GT;&#34; DWd1HEcBC3DhUahfOQcdaY0 /则oE + VHapxxE + HPUb0I6iSiqMxkz6l + VLK + 1zhb66HnZ / vZRUVG4ojTdWUCjHtGg ==&#34 ;,    &#34;费用&#34; =&gt; {&#34;标题&#34; =&gt;&#34;测试&#34;,&#34;价值&#34; =&gt;&#34; -20&# 34;,&#34; category_id&#34; =&gt;&#34; 1&#34;,&#34; payee_id&#34; =&gt;&#34; 2&#34;,&#34; date&#34 ; =&gt;&#34; 2018-01-21&#34;,&#34; account_id&#34; =&gt;&#34; 1&#34;,&#34;评论&#34; =&gt;&# 34;&#34;},    &#34;提交&#34; = GT;&#34;提交&#34;}

2 个答案:

答案 0 :(得分:0)

我首先要评论所有模型验证,然后创建费用。每次添加一个模型验证,每次测试创建费用以查看导致错误的验证。

您也可能想要改变如何将费用创建为以下内容。

将您的控制器创建操作更改为

def create
  @expense = Expense.new(expense_params)   
  if @expense.save
    flash[:success] = "expense created"
    redirect_to expense_url(@expense.id)
  else
    render 'new'
  end
end

接下来在控制器底部的私有方法下,你想做类似的事情

private
    # Never trust parameters from the scary internet, only allow the white list through.
    def expense_params
      params.require(:expense).permit(:title, :value, :date, etc...)
    end

答案 1 :(得分:0)

我终于找到了问题所在!正是类/模型的命名引发了错误。我已经将我的模型命名为单数(AccountCategory等),而所有引用都在搜索复数(AccountsCategories等)。我必须从一开始就重新进行所有迁移,以使其正常工作!

感谢大家花的时间!