How do you access params[:model][:field] in Rails 4? -
from understand...
- if have
form_for @model
,params[:model]
available when form submitted. furthermore, if form has 2 attributesattr1
,attr2
,params[:model][:attr1]
,params[:model][:attr2]
available when form submitted. - in rails 4, you're supposed write method
model_params
saysparams.require(:model).permit(:attr1, :attr2)
. - you'd use
model_params
so:model.new(model_params)
.
however, do if need 1 of fields form? if needed params[:model][:attr1]
?
example:
def create @user = user.new(user_params) if @user.save # need access params[:user][:password] here redirect_to root_url, :notice => "signed up!" else render :new end end private def user_params params.require(:user).permit(:email, :password, :password_confirmation) end
the gem responsible behaviour strong_parameters
. permit()
method decides pass on model based on attributes pass it.
in case, passed :attr1
, :attr2
:
params.require(:model).permit(:attr1, :attr2)
this means model have attr1
, attr2
set whatever values passed form.
if wanted set attr1
, remove attr2
permit()
call.
params.require(:model).permit(:attr1)
you model not have attr1
set, not attr2
. it's simple.
you can permit (not recommended) calling permit!
bang , no arguments.
you can read more behaviour on the gem's github project page.
update based on op's edit
if need access params[:user][:password]
in controller... well, accessed in example. accessed typing params[:user][:password]
.
nothing prevents accessing params hash directly. strong_parameter's job prevent mass assigning hash model, that's all.
Comments
Post a Comment