新手问题 Rails fixture 机制

Focinfi · September 20, 2014 · Last by Focinfi replied at September 20, 2014 · 2263 hits

Rails 新手,在看书《Agile Web Development With Rails 4》

在 Check Out 这一节,新建了 scaffold Order 和 migration add_order_to_line_item

这里我忘记了在 models/line_item.rb 添加 belongs_to :order

但是创建订单的功能并没有问题,直到修改 fixtures/line_items.yml 成:

one:
  product: mac
  order: one

测试时报错:table line_items has no column named order

所以,我的理解是: 1.model 中的 belongs_to 和 has_many 都是只是说明自己和别人的关系。在功能上 Order 只是创建 LineItem,所以只要在 models/order.rb 写 has_many :line_items,代码就能跑起来。

2.而当跑测试时,要将 fixtures/..的数据 insert 到数据库,而此时在 models/line_item.rb 中没有 belongs_to :order,数据库 line_items 表就不知道有外键 order_id,所以会报上面的错误。

不知道我的理解有没有问题,还请各位前辈指点。

fixture 用的人不多了。

大部分人都在用 FactoryGirl,生成依赖关系时更简洁。

FactoryGirl.define do
  factory :line_item do
    product        { FactoryGirl.create :product_mac }
    quantity        3
    total_price    45_000
    order             { FactoryGirl.create :order }
  end
end

@xiaoronglv 谢谢你的帮助

You need to Sign in before reply, if you don't have an account, please Sign up first.