Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - ActiveRecord .select(): Possible to clear old selects?

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

Background:

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)
}

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")

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...