我在使用设计的小项目中使用strong parameters gem
我添加了User.rb
一个locale
列。这是我的controllers/users/registrations_controller.rb
文件:
class Users::RegistrationsController < Devise::RegistrationsController
def resource_params
params.require(:user).permit(:username, :email, :password, :password_confirmation, :locale)
end
private :resource_params
def create
#add params[:locale] to resource.locale here
super
end
end
这些是从表格中收到的参数:
Parameters: {"authenticity_token"=>"ZyrtToHcwsX3zl2ive93cpYaom6HNGA/jnYcSg7pQUQ=", "user"=>{"username"=>"hyperrjas@hyperrjas.com", "email"=>"email@email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create account", "locale"=>"es"}
我想添加user :locale column
参数params[:locale]
我该怎么做?
谢谢!
答案 0 :(得分:0)
我已修复了从此doc中覆盖create
方法的问题:
如果您想使用column or field locale
向模型用户添加指定strong parameters gem
,则可以在下一个时间添加controllers/users/registrations_controller.rb
:
class Users::RegistrationsController < Devise::RegistrationsController
def create
build_resource
resource.locale = set_locale #set_locale or where you have stored your own locale
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
def resource_params
params.require(:user).permit(:username, :email, :password, :password_confirmation, :locale)
end
private :resource_params
end
问候!
答案 1 :(得分:0)
在视图中处理它。
您的观点可能类似于:
<%= form_for :user do |f| %>
<%= f.username %>
<%= f.password %>
<%= # Etc... %>
<% end >
<%= select_tag :locale, options_from_collection_for_select(I18n.config.available_locales, :to_s, :to_s), :selected => user.locale %>
因此,请将其更改为:
<%= form_for :user do |f| %>
<%= f.collection_select :locale, I18n.config.available_locales, :to_s, :to_s, :selected => user.locale %>
<%= f.username %>
<%= f.password %>
<%= # Etc... %>
<% end >
这样,params对象就会在locale
中嵌套user
。
选项1的缺点是您的区域设置选择可能位于导航栏中,将其移动到表单中是没有意义的。但是,您可以维护2个字段 - 现有导航栏一个,并在表单中隐藏。
<%= form_for :user do |f| %>
<%= f.hidden_field :locale, value => user.locale %>
<%= f.username %>
<%= f.password %>
<%= # Etc... %>
<% end >
在提交之前使用Javascript将值从导航栏字段复制到隐藏字段:
$('form').on('submit', function(){
$("#user_locale").val($("#locale").val());
});
在设置强参数之前将其复制到控制器中:
class Users::RegistrationsController < Devise::RegistrationsController
private
def resource_params
params[:user][:locale] = params[:locale]
params.require(:user).permit(:username, :email, :password, :password_confirmation, :locale)
end
end
所有这些都是接受答案的更好的替代品,因为它们避免了代码重复。每次要升级设计时,您都不必再次复制和粘贴。