我正在运行ruby 1.9.3和rails 4.1.4在models \ profile.rb中尝试以下验证
attr_accessor :password
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :password, :confirmation => true #password_confirmation attr
validates_length_of:password,:in => 6..20,:on =>:create before_save:encrypt_password
在表单中查看profile \ new.html.erb
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</p>
<p>
<%= f.label :interests %><br />
<%= f.text_area :interests %>
</p>
<p>
<%= f.label :zip %><br />
<%= f.text_field :zip %>
</p>
<p>
<%= f.label :country %><br />
<%= f.country_select :country, ["United Kingdom"] %> </p>
使用强参数controllers \ profile_controller,rb
class ProfilesController < ApplicationController
def new
@profile = Profile.new
end
def create
@profile = Profile.new(params[profile_params])
if @profile.save
flash[:notice] = "You signed up successfully"
flash[:color]= "valid"
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
end
render "new"
end
private
## Strong Parameters
def profile_params
params.require(:profile).permit(:name, :email, :password, :interests,:zip)
end
end
验证总是失败,说明字段为空。通过引发异常,报告将显示模型配置文件及其字段。好像数据根本无法访问,所以我怀疑我是在错误地使用强参数。
欢迎任何意见。
该profile_params
函数将直接为您返回带有数据的哈希。
基本上,它的工作是过滤params
名称为的参数的键的“配置文件”键值的哈希值,permit(...)
因此解决方法是编写
@profile = Profile.new(profile_params)
代替
@profile = Profile.new(params[profile_params])
使用强大的参数,您几乎永远不会params
直接通过控制器操作(例如create
)与数组进行交互。私有强参数方法将为您处理此问题,并且仅将安全的,经过过滤的数据提供给您的控制器操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句