rails 4 strong params + dynamic hstore keys

帅比萌擦擦* 提交于 2019-11-27 14:07:18

问题


I'm having a problem overcoming the new strong params requirement in Rails 4 using Hstore and dynamic accessors

I have an Hstore column called :content which I want to use to store content in multiple languages, ie :en, :fr, etc. And I don't know which language upfront to set them in either the model or the controller.

store_accessor :content, [:en, :fr] #+226 random other il8n languages won't work.

How can I override strong params (or allow for dynamic hstore keys) in rails 4 for one column?

  params.require(:article).permit(
    :name, :content,
    :en, :fr #+226 random translations
  )

Short of...

params.require(:article).permit!

which of course does work.


回答1:


If I understand correctly, you would like to whitelist a hash of dynamic keys. You can use some ruby code as follows to do this:

params.require(:article).permit(:name).tap do |whitelisted|
  whitelisted[:content] = params[:article][:content] 
end

This worked for me, hope it helps!




回答2:


I'm doing something similar and found this to be a bit cleaner and work well.

Assuming a model called Article you can access your :content indexed stored_attributes like this: Article.stored_attributes[:content]

So your strong params looks like this:

params.require(:article).permit(:name, content: Article.stored_attributes[:content])

Assuming your params are structured like: { article => { name : "", content : [en, fr,..] } }




回答3:


As people have said, it is not enough to permit the :content param - you need to permit the keys in the hash as well. Keeping things in the policy, I did that like so:

  # in controller...

  def model_params
    params.permit(*@policy.permitted_params(params))
  end  

  # in policy...

  def permitted_params(in_params = {})
    params = []

    params << :foo
    params << :bar

    # ghetto hack support to get permitted params to handle hashes with keys or without

    if in_params.has_key?(:content)
      content = in_params[:content]
      params << { :content => content.empty? ? {} : content.keys }
    end
  end


来源:https://stackoverflow.com/questions/17348703/rails-4-strong-params-dynamic-hstore-keys

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