【问题标题】:rails database query is resulting activeRecord::Relationrails 数据库查询结果为 activeRecord::Relation
【发布时间】:2013-05-29 14:24:54
【问题描述】:

我正在使用 Spree Commerce 开发我的电子商务网站。当我写

self.where("user_id = ?", user_id)**

为了访问数据库,它显示ActiveRecord::Relation,当我使用时

self.where("user_id = ?", user_id).first

它没有返回任何东西。我正在使用

Spree::Modelname.actionname 在视图文件中访问数据。

谁能帮我从 Rails 3.2 的数据库中获取数据。

【问题讨论】:

  • 你确定 self 就是你在执行语句时认为的样子吗?
  • 我也尝试将 self 更改为 Spree::Wishlist,但它也显示了相同的结果。

标签: ruby-on-rails database activerecord spree


【解决方案1】:

.where(...) 在模型类上调用将返回一个关系。如果是单条记录,您可以调用.first.last,或者为一组记录调用.all.to_a.limit(...)

如果这不起作用,请确保您使用的是 Spree 用户类:

Spree.user_class.where("user_id = ?", user_id).first

或:

Spree.user_class.where(:user_id => user_id).first

或 Ruby 1.9+ 哈希语法:

Spree.user_class.where(user_id: user_id).first

假设 Spree 的用户类是由具有“user_id”列的表支持的模型,并且数据库表中有一条记录,其 user_id 等于您传入的 user_id。

【讨论】:

  • 是的,这个查询工作正常。但我实际上是在我的网站中添加了 spree-wishlist 扩展,我想在主页中生成一个指向愿望清单的链接。所以当我用愿望清单模型尝试同样的事情时,它没有显示任何东西。
  • 对于愿望清单,它看起来像是 Spree::Wishlist.where(:name => "some wishlist name") 或通过 user_id 查找愿望清单,Spree::Wishlist.joins(Spree.user_class.table_name.to_sym).where(Spree.user_class.table_name.to_sym => {:user_id => user_id}).first。可能希望将所有 Spree.user_class 和 Spree.user_class.table_name.to_sym 替换为这些值,以免混淆代码,除非您正在编写通用扩展/gem。
  • 如果您还没有 SQL,请务必通读 this,并在此之前充分了解 SQL,因为随着时间的推移您会需要它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 2011-10-19
  • 2018-01-31
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 2013-02-18
相关资源
最近更新 更多