查询嵌套模型属性时出错

时间:2015-03-23 23:17:02

标签: ruby-on-rails-4

我的模特:

OrderStatus 
  belongs_to Order

Order
  has_one OrderStatus
  belongs_to Logo

Logo
  has_many Orders

我想对名为artwork的Logo模型属性执行查询:

OrderStatus.includes({:order => :logo}).where(:order => {:logo => {:artwork => search_artwork}})

但它基本上会抛出一个错误:

SQLite3::SQLException: no such column: order.logo: SELECT COUNT(DISTINCT "order_statuses"."id") FROM "order_statuses" LEFT OUTER JOIN "orders" ON "orders"."id" = "order_statuses"."order_id" LEFT OUTER JOIN "logos" ON "logos"."id" = "orders"."logo_id" WHERE "order"."logo" = '--- :artwork: xxxxxxx'

我看不出这个错误的原因。

修改

经过广泛搜索后,我意识到部分应该使用表名(即复数),所以我的代码应该是

@order_statuses = OrderStatus.includes(:order => [:logo]).where(:orders => {:logos => {:artwork => search_artwork}})

但我仍然看到SQLite3异常错误

SQLite3::SQLException: no such column: orders.logos: SELECT COUNT(DISTINCT "order_statuses"."id") FROM "order_statuses" LEFT OUTER JOIN "orders" ON "orders"."id" = "order_statuses"."order_id" LEFT OUTER JOIN "logos" ON "logos"."id" = "orders"."logo_id" WHERE "orders"."logos" = '--- :artwork: xxxxxxxx '

1 个答案:

答案 0 :(得分:0)

快速回答

  

我仍然看到SQLite3异常错误... temp16"

您的inFile.read(reinterpret_cast<char*>(&temp16), 2); 表格是否没有名为no such column: orders.logos的列,它有一个名为orders的列,该列是在您在评论中提到的迁移中创建的。

发生此错误的原因是Rails并不理解(据我所知)logos子句中的嵌套值。

也许更重要的是,我认为您(可能)更感兴趣的是:

  • 如何编写逻辑,为logo_id提供与.where相关的所有OrderStatusLogo值等于artwork

如果是这样,为search_artwork模型添加has_one :through关系会让这很容易!

Logo

然后,您的查询应该如下:

Logo.where(artwork:search_artwork).includes(:orderStatus)

编辑:oops以上是错误的

OrderStatus 
  belongs_to Order

Order
  has_one OrderStatus
  belongs_to Logo

Logo
  has_many Orders
  has_many OrderStatuses, :through => :Order # This is what you're adding!

有关Rails关系和使用Logo.where(artwork: search_artwork).order_statuses 的更多信息,请参阅: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association