Ruby on Rails的:从默认选择列prevent [英] Ruby on Rails: prevent from selecting a column by default

查看:126
本文介绍了Ruby on Rails的:从默认选择列prevent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有输入表与内容字段可能包含大量的文字。在大多数情况下,我并不需要获得该领域,所以它似乎是资源的巨大浪费,每次从数据库中加载了大量未使用的数据(SELECT * FROM项其中id = 1)。

I have entries table with a content field which might contain a lot of text. In most cases I don't need to access that field, so it seems to be a big waste of resources to every time load a huge amount of unused data from the database (select * from entries where id = 1).

我怎么能指定default_scope,所有除了内容领域将被从数据库加载?

How could I specify the default_scope, that all the fields apart from content would be loaded from database?

推荐答案

假设的Rails 3和看起来像这样一个模式:

Assuming Rails 3 and a schema that looks like this:

create_table "entries", :force => true do |t|
  t.string   "title"
  t.text     "content"
  t.datetime "created_at"
  t.datetime "updated_at"
end

您可以使用选择的方法来限制​​返回类似这样的字段:

You can use the select method to limit the fields that are returned like this:

class Entry < ActiveRecord::Base
  default_scope select([:id, :title])
end

在轨控制台,你会看到这样的事情:

In the rails console, you should see something like this:

puts Entry.where(:id => 1).to_sql  # => SELECT id, title FROM "entries"  WHERE "entries"."id" = 1

当你要选择所有的字段,您可以使用无范围这样的方法:

When you do want to select all of the fields, you can use the unscoped method like this:

puts Entry.unscoped.where(:id => 1).to_sql  # => SELECT * FROM "entries"  WHERE "entries"."id" = 1

这篇关于Ruby on Rails的:从默认选择列prevent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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