简体   繁体   中英

What's the best way to protect certain records from modification or deletion?

I have three models: user, subscription, and channel.

User:

has_many :channels, :through => :subscriptions

Subscription:

belongs_to :user
belongs_to :channel

Channel

belongs_to :user
has_many :users, :through => :subscriptions

I have an after_create method that automatically adds the creating user of a channel to the subscriptions table with some other necessary attributes set. How and where should I add the prevention of the deletion or modification of subscription record that corresponds to the the channel's user?

Because my models can be updated from a few different actions in different controllers, I need this in the model layer, but I'm not sure which callback I should use. Do I need to write a validation or do I need to hook in to before_destroy , after_destroy or what?

Rails 3.1.3

If you need to prevent the deletion or modification of the Subscription record unless certain criteria are met, I'd put those protections in the Subscription model's before_destroy and before_save hooks. If your criteria for modifying and deleting are the same they can both point to the same method; otherwise you can specify before_destroy :validate_destroy_privileges and before_save validate_save_privileges , or whatever makes semantic sense to what you're checking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM