How to make changes to strong parameters (change to lowercase)

后端 未结 4 1413
予麋鹿
予麋鹿 2020-12-16 18:42

So I am familiarising myself with both rails and of course rails 4.

So this is what I have at the bottom of my controller

def post_params
  params.re         


        
相关标签:
4条回答
  • 2020-12-16 19:17

    Better You can use before_create callback to update the value.

    like,

    before_create :check_params
    
    def check_params   
       self.category.downcase!     
    end
    
    0 讨论(0)
  • 2020-12-16 19:29

    The strong_params function is just about giving your controller a "whitelist" of variables to work with. It's really for security purposes, and literally just means that your app can access params[:permitted_param] to save the data.


    There are 2 things you could do:

    --> Edit the params[:category] variable before you call the post_params function:

    def create
        params[:category].downcase
        @post = Post.new(post_params)
        @post.save
    end
    

    --> You could use the before_create function as recommended by @thiyaram too :)

    0 讨论(0)
  • 2020-12-16 19:34

    Do this:-

    before_create :downcase_category
    
    def downcase_category
     self.category.downcase!
    end
    
    0 讨论(0)
  • 2020-12-16 19:43

    If you're on Rails 4 this might not work: the parameters that you tamper with are no longer accepted even if you explicitly whitelist them via strong params.

    It looks like Rails is detecting the change and prevents it from being permitted.

    Probably a better way is to retrieve the values from the parameters in a controller action and make them lowercase:

    a = params([:model_name][:id])
    a.downcase!
    
    0 讨论(0)
提交回复
热议问题