问题
Till now I thought, I have to permit only those attributes which I required to save in database. But recently I used Jcrop to crop my User avatar and it has 4 virtual attributes which will be sent after crop from the front end,
Here is my model
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
after_update :crop_avatar
def crop_avatar
avatar.recreate_versions! if crop_x.present?
end
end
When I submit after crop, my console log says
unpermitted params: crop_x, crop_y, crop_h, crop_w
and the image is not cropped.
But if I permit these virtual attributes as
params.require(:user).permit(:avatar,:crop_x,:crop_y,:crop_h,:crop_w)
then image were cropped successfully.
So the question is why do I need to permit these virtual attributes, even if this is not saved in database?
回答1:
From the Rails guide:
With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted.
So there is no discrimination between normal and virtual attributes here, it is just about allowing parameters for mass assignment. What your model does with those parameters is up to you.
来源:https://stackoverflow.com/questions/22034872/do-we-need-to-permit-ruby-virtual-attributes-also