开发者

Retrieving only certain columns with Rails 3 where clause

开发者 https://www.devze.com 2023-03-19 06:00 出处:网络
Not sure why I can\'t find out how to do this easily... Obviously I could do it with raw SQL, but I\'m trying to familiarize myself with ActiveRecord.

Not sure why I can't find out how to do this easily... Obviously I could do it with raw SQL, but I'm trying to familiarize myself with ActiveRecord.

results = Model.where(:lat => (south..north), :lng => (east..west))

I don't want all the fields, just a few.开发者_JAVA百科 How would I limit the results to only include columns I choose?


results = Model.where(:lat => (south..north), :lng => (east..west)).select([:lat, :long, :id])

You'll also probably want to include the :id in that select if you want your results to behave like reasonable ActiveRecord objects.

Edit: Select takes a single arg, can be an array.


You need to use select

Model.where(...).select(...)

select accept array or raw sql string.

http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields


Technically, if you want to reuse the data subset filter for readonly models, you can create a 'view' at the database level. See http://dev.mysql.com/doc/refman/5.0/en/views.html

0

精彩评论

暂无评论...
验证码 换一张
取 消