Do we need to permit ruby virtual attributes also?

天大地大妈咪最大 提交于 2020-01-25 03:17:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!