Is there a way to make Rails ActiveRecord attributes private?

前端 未结 7 828
渐次进展
渐次进展 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:26

    Making the setting private does generate ActiveRecord error.

    I put access control code in the overwritten method of the public setter by checking the caller:

    def my_private_attribute=(val)
      if (caller.first.include?('active_record/base.rb') || caller.first.include?('app/models/myclass.rb'))
        self[:my_private_attribute] = val
      else
         raise Exception.new("Cannot set read-only attribute.")
      end
    end
    
    0 讨论(0)
提交回复
热议问题