使用 sqlite3 创建模型 +数据映射器 +红宝石
如何构建具有以下关联的模型(我尝试过,但无法使其工作):
每个订单都有:一个客户、一个销售代表、许多 OrderLine,每个订单都有一个项目。
我尝试过:当我这样做时:Customer.all(Customer.orders.order_lines.item.sku.like => "%BLUE%") 输出是:[]
而不是: '[#<"Customer @id=1 @name="Dan Kubb">]'
当我删除 SalesRep 时:它有效。Customer
有 n 个,:订单
有 n, :items, :through => :订购
销售代表
有 n 个,:订单
有 n, :items, :through => :订购
订单
属于:客户
属于:技术员
有 n, :order_lines
有 n, :items, :through => :订单行
订单行
属于:订单
属于:项目
项目
有 n, :order_lines
How do you build a model with the following associations (i tried but couldn't get it to work):
each Order has: a Customer, a SalesRep, many OrderLine that each has an item.
I tried: when I do: Customer.all(Customer.orders.order_lines.item.sku.like => "%BLUE%")
the output is :[]
instead of: '[#<"Customer @id=1 @name="Dan Kubb">]'
When I delete SalesRep: it works.
Customer
has n, :orders
has n, :items, :through => :order
SalesRep
has n, :orders
has n, :items, :through => :order
Order
belongs_to :customer
belongs_to :technician
has n, :order_lines
has n, :items, :through => :order_line
OrderLine
belongs_to :order
belongs_to :item
Item
has n, :order_lines
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于输出不是错误,因此可能是您的数据库中实际上没有数据。
使用
irb -r your_models_file.rb
尝试以下操作:-
c = Customer.create(:name => "Dan Kubb")
o = Order.new(:customer => c) # 创建并添加技术人员,除非是 :required = > false
i = Item.create(:sku => "BLUE") # 加上任何其他必填字段
ol = OrderLine.create(:order => o, : item => i)
o.order_lines <<哦; o.save
这应该创建此操作所需的记录。尝试一下,如果不起作用,请发布您的整个模型文件,以便我们更好地了解发生了什么。
Since the output isn't an error, it could be that you don't actually have the data in your database.
Try the following with
irb -r your_models_file.rb
:-
c = Customer.create(:name => "Dan Kubb")
o = Order.new(:customer => c) # Create and add technician unless it's :required => false
i = Item.create(:sku => "BLUE") # Plus any other required fields
ol = OrderLine.create(:order => o, :item => i)
o.order_lines << ol; o.save
That should create the records needed for this to work. Try this out, and if it doesn't work, post your entire models file so we can get a better idea of what's up.