2

I read this post on

In Rails, how do I limit which attributes can be updated, without preventing them from being created?

They problem is that the u.save returns true, so it give the impression that all the values got updated. When they did not.

Is there a way to use attr-readonly, but on save return false if an attribute is read only?

class User < ActiveRecord::Base
  attr_accessible :name
  attr_readonly :name
end


> User.create(name: "lorem")
> u = User.first
=> #<User id: 1, name: "lorem">
> u.name = "ipsum"
=> "ipsum"
> u.save
=> true
> User.first.name
=> "lorem
user2012677
  • 5,465
  • 6
  • 51
  • 113

1 Answers1

2

You can use a validator method to write an error on changes detected to your read only field

Class User
  validate :name_not_changed

  private

  def name_not_changed
    return unless name_changed?

    errors.add(:name, 'Cannot change name of User')
  end
end

Is this really necessary though? If you're making your attribute read-only, why are you still leaving the possibility for it to be changed and additionally need validation errors for that operation? Ideally, you shouldn't permit the name to ever be used when updating models and the story ends there, no validation errors needed.

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177