新手问题 Rails fixture 机制

Focinfi · 2014年09月20日 · 最后由 Focinfi 回复于 2014年09月20日 · 2260 次阅读

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 谢谢你的帮助

需要 登录 后方可回复, 如果你还没有账号请 注册新账号