Validation 字段不为空时验证失败为空

Validation 字段不为空时验证失败为空,validation,Validation,我正在运行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 att

我正在运行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
验证以下内容的长度:password,:in=>6..20,:on=>:create 保存前:加密密码

查看配置文件中\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>
使用强参数控制器\profile\u控制器,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
验证总是失败,因为字段为空。通过引发异常,报告将显示模型配置文件及其填充的字段。这就好像数据根本无法访问,所以我怀疑我使用的是强参数sonehow。 欢迎发表任何意见。

profile_params函数将直接为您返回包含数据的哈希值。 它的基本功能是过滤参数散列中的'profile'键的值,这些键被命名为permit的参数。。。 所以解决问题的方法就是写

@profile = Profile.new(profile_params)
而不是

@profile = Profile.new(params[profile_params])

对于强参数,您几乎从不直接从控制器操作(如创建)与params数组交互。私有强参数方法将为您处理这些问题,这样,只有安全的、过滤过的数据才会提供给您的控制器操作。

太棒了,工作正常。谢谢你的帮助和教育。不客气。你能考虑接受我的回答吗?当然可以。我该怎么做?