softcode
softcode

Reputation: 4658

attr_readonly After Update

Is there was a way to assign attr_readonly after update?

attr_readonly, on: :update

If not, perhaps a method

@post.update(content: params[:content])
@post.readonly 

Upvotes: 0

Views: 924

Answers (3)

spickermann
spickermann

Reputation: 106972

You could override readonly? in that model like this:

def readonly?
  super || created_at != updated_at
end

Rails checks if a record is readonly before it tries to saves an updated record to the database and would raise an ActiveRecord::ReadOnlyRecord exception if the record is marked as readonly. This overridden readonly? method protects a record from being changed twice, by returning always true if the record was changed at least once (indicated by different timestamp on updated_at and created_at).

Furthermore this allows you to check in your view item.readonly? to hide links to the edit page.

Upvotes: 2

Papouche Guinslyzinho
Papouche Guinslyzinho

Reputation: 5458

You can add a count into your Model

rails g scaffold sport name
rails g migration add_modified_count_to_sports modified_count:integer

I'm assigning a default value

class AddModifiedCountToSports < ActiveRecord::Migration
  def change
    add_column :sports, :modified_count, :integer, default: 0
  end
end

rake db:migrate

On my Sport model I create a before_update sort of validation

class Sport < ActiveRecord::Base

  before_update :validate_update_status

  def validate_update_status
    unless self.modified_count.eql?(1)
        #if the field 'modified_count = 0'
        self.modified_count = 1
    else
        errors.add(:name,'You can only modified your account once')
        false
    end#end unless

  end#def

end#class

You could also implement the same with a State Machine like gem (i.e. assm) voilà!

Upvotes: 0

PGill
PGill

Reputation: 3521

you can create a before_update

 before_update :forbid_second_update

 def forbid_second_update
   if created_at != updated_at_was
     errors.add :base, "Cannot updated!"
     false
   end
 end

first time update will be successful as created_at and updated_at will be same

second time it will fail

or alternatively if you want to lock some attributes and don't want to fail the update, you can just add for eg.

 self.email = self.email_was 

this will override the email attribute to its old value

Upvotes: 0

Related Questions