ActiveRecord .select():可以清除旧的选择吗? [英] ActiveRecord .select(): Possible to clear old selects?

查看:29
本文介绍了ActiveRecord .select():可以清除旧的选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法清除 .select("table.col1, ...") 语句中的旧选择?

Is there a way to clear old selects in a .select("table.col1, ...") statement?

背景:

我有一个范围为给定的用户 ID(简化)请求可访问的项目

I have a scope that requests accessible items for a given user id (simplified)

    scope :accessible, lambda { |user_id|
  joins(:users).select("items.*")
    .where("items_users.user_id = ?) OR items.created_by = ?", user_id, user_id)
}

然后例如在索引操作中我只需要项目 ID 和标题,所以我会这样做:

Then for example in the index action i only need the item id and title, so i would do this:

@items = Item.accessible(@auth.id).select("polls.id, polls.title")

但是,这将选择列items.、items.id、items.title".我想避免从范围中删除选择,因为那时我必须在其他地方添加一个 select("items.") .我认为没有办法做到这一点是否正确,我要么忍受获取太多字段,要么不得不使用多个范围?

However, this will select the columns "items., items.id, items.title". I'd like to avoid removing the select from the scope, since then i'd have to add a select("items.") everywhere else. Am I right to assume that there is no way to do this, and i either live with fetching too many fields or have to use multiple scopes?

推荐答案

幸运的是你错了 :D,你可以使用 #except 方法删除关系所做的查询的某些部分,因此如果您想删除 SELECT 部分,请执行以下操作:

Fortunately you're wrong :D, you can use the #except method to remove some parts of the query made by the relation, so if you want to remove the SELECT part just do :

@items = Item.accessible(@auth.id).except(:select).select("polls.id, polls.title")

这篇关于ActiveRecord .select():可以清除旧的选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆