user233232
user233232

Reputation: 6217

Rails defined which fields will return from model

I have a model in rails, for example 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

What i want to do is control which fields returning by default when i am query my model, so for example lets say i want to return only the title field in every query, without using select. i am coming from laravel and there i can do this. How i can do this in rails?

Upvotes: 1

Views: 94

Answers (1)

Vishnu Atrai
Vishnu Atrai

Reputation: 2368

You can use ActiveRecord default_scope that will be added with all the queries be default.

class Post < ActiveRecord::Base
  default_scope { select('id, title') }
end 

Upvotes: 2

Related Questions