Arel表格查询 - > has_one

发布于 2025-02-05 19:28:47 字数 585 浏览 1 评论 0原文

我正在尝试使用AREL表查询来对HAS_ONE关系进行“ WHERE”查询。 has_one关系是必要的,因为当前设置为“ has_one_through”。

使用AREL表查询的原因是此查询逻辑将是动态的。有几种has_one关系需要单独查询,因此我想尽可能干燥和可扩展。

我试图复制的查询看起来有点像这样。

查询我要复制('style/s'关键字将是动态的)

Book.includes(:style).where(styles: {id: 8})

我到目前为止尝试的

object = Style.find(8)
object_key = object.model_name.i18n_key
object_table = Arel::Table.new(object_key)
has_one = object_table[:id].eq(object.id)

Book.includes(object_key).where(has_one)

I am trying to use an arel table query to perform a 'where' query on a has_one relationship. The has_one relationship is necessary as it's currently set up as a 'has_one_through'.

The reason for using an arel table query is that this query logic will be dynamic. There are several has_one relationships that need to be queried separately so I want to be as dry and scalable as possible.

The query I am trying to replicate looks a little like this.

Query I want to replicate ('style/s' keyword would be dynamic)

Book.includes(:style).where(styles: {id: 8})

What I've tried so far

object = Style.find(8)
object_key = object.model_name.i18n_key
object_table = Arel::Table.new(object_key)
has_one = object_table[:id].eq(object.id)

Book.includes(object_key).where(has_one)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白龙吟 2025-02-12 19:28:47

下实现此目的

object = Style.find(8)
object_key = object.model_name.i18n_key

Book.includes(object_key).where(object_key.to_s.pluralize => { id: object.id })

您可以在不使用arel的情况 下一步:

object = Style.find(8)
object_key = object.model_name.i18n_key
object_table = Arel::Table.new(object_key.to_s.pluralize)
Book.joins(object_key).where(object_table[:id].eq(object.id))

You can achieve this without using Arel by using pluralize on the object_key

object = Style.find(8)
object_key = object.model_name.i18n_key

Book.includes(object_key).where(object_key.to_s.pluralize => { id: object.id })

If you want to use Arel anyway you can do next:

object = Style.find(8)
object_key = object.model_name.i18n_key
object_table = Arel::Table.new(object_key.to_s.pluralize)
Book.joins(object_key).where(object_table[:id].eq(object.id))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文