Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails定义了从模型返回的字段_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails Rails定义了从模型返回的字段

Ruby on rails Rails定义了从模型返回的字段,ruby-on-rails,ruby,Ruby On Rails,Ruby,我在rails中有一个模型,例如Post.rb: class Post < ActiveRecord::Base end class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.text :title t.text :answer t.timestamps end end end class Post

我在rails中有一个模型,例如Post.rb:

class Post < ActiveRecord::Base

end

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.text :title
      t.text :answer
      t.timestamps
    end
  end
end
class Post

我想做的是控制在查询模型时默认返回哪些字段,例如,假设我只想在每个查询中返回标题字段,而不使用select。我来自拉雷维尔,在那里我可以做到这一点。如何在rails中做到这一点?

您可以使用
ActiveRecord
default\u scope
,它将与所有默认查询一起添加

class Post < ActiveRecord::Base
  default_scope { select('id, title') }
end 
class Post
这不起作用,我正在获取所有字段和id:null@user233232如果您想要id和标题,可以用逗号分隔的字符串表示。ie
default\u scope{select('id,title')}
@VishnuAtrai您应该传递多个参数,即
select('id','title')
select(:id,:title)
试试这个:default\u scope->{select('your\u field\u name')}