有没有办法清除 .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():可以清除旧的选择吗?
发布评论