Is there a way to make Rails ActiveRecord attributes private?

前端 未结 7 856
渐次进展
渐次进展 2020-12-08 13:48

By default, ActiveRecord takes all fields from the corresponding database table and creates public attributes for all of them.

I think that it\'s reasonable not<

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 14:23

    Stumbled upon this recently. If you want private writing and reading and public reading something like this

    class YourModel < ActiveRecord::Base
    
      attr_reader :attribute
    
      private
    
      attr_accessor :attribute
    
    
    end
    

    seems to work fine for me. You can fiddle with attr_reader, attr_writer and attr_accessor to decide what should be exposed and what should be private.

提交回复
热议问题