【问题标题】:Testing association through aliases通过别名测试关联
【发布时间】:2013-05-30 17:31:00
【问题描述】:

我是 TDD 和 Rails 的新手。 我正在尝试测试一个“别名”关联(不知道这是否是一个有效术语)。

我的测试:

it 'an order should always have a customer' do
  o = Order.new
  o.should_not be_valid
end

我的模特:

class Order < ActiveRecord::Base
  belongs_to :customer, :class_name => Person
  validates_associated :customer
end

我不知道 validates_associated 是否符合它的暗示。我的测试仍然将带有“customer_id:nil”的订单视为有效。

Person 模型:

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :middle_name
  validates_presence_of :first_name, :last_name

  has_many :addresses
  has_many :orders, :as => :customer
end

我想确保保存的每个订单都有一个关联的客户(一个 Person 对象)。 我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec rspec-rails


    【解决方案1】:

    validates_associated 仅告诉模型也应在关联对象上运行验证(查看文档here)。您仍然需要在 Order 上添加验证。看看this SO question。我可能是错的,但我认为它会为您指明您正在寻找的方向。

    【讨论】:

    • 我添加了一个 validates_presence_of,它似乎正在工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多