How to make changes to strong parameters (change t

2019-01-25 09: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.require(:post).permit(:title, :content, :category)
end

Which works fine, but what I would like to do is work out how to access those parameters individually either in the post_params method, or later in the controller.

Specifically I would like to change the :category value to lower case before making use of the parameter in creating the post (so that within the table all categories are in lowercase).

EDIT: perhaps a better phrasing to my question is, after permitting the parameters, how can i access and manipulate them afterwards..can I just use params[:title] as usual?

I have tried

params.require(:post).permit(:title, :content, :category)
params[:category].downcase

and

params.require(:post).permit(:title, :content)
params.require(:post).permit(:category).downcase

But I get undefined method 'downcase'

4条回答
地球回转人心会变
2楼-- · 2019-01-25 10:20

Do this:-

before_create :downcase_category

def downcase_category
 self.category.downcase!
end
查看更多
对你真心纯属浪费
3楼-- · 2019-01-25 10:26

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!
查看更多
迷人小祖宗
4楼-- · 2019-01-25 10:27

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 :)

查看更多
Deceive 欺骗
5楼-- · 2019-01-25 10:30

Better You can use before_create callback to update the value.

like,

before_create :check_params

def check_params   
   self.category.downcase!     
end
查看更多
登录 后发表回答