2016-02-11 102 views
0

我有一个表单,我正在使用if语句来从@ current_user.name(adauth)拉取用户名,如果表单是新的,则@ complaint.user.name如果表单是正在编辑。NoMethodError /验证不起作用

的验证是工作,但现在,如果我尝试提交一个空的形式或形式,其中相关的字段值是零,然后我得到投诉

NoMethodError in Complaints#create 
Showing C:/Users/cmendla/RubymineProjects/internal_complaints/app/views/complaints/_form.html.erb where line #27 raised: 

undefined method `name' for nil:NilClass 
Trace of template inclusion: app/views/complaints/new.html.erb 

Rails.root: C:/Users/cmendla/RubymineProjects/internal_complaints 

Application Trace | Framework Trace | Full Trace 
app/views/complaints/_form.html.erb:27:in `block in _app_views_complaints__form_html_erb__838826376_68516916' 
app/views/complaints/_form.html.erb:1:in `_app_views_complaints__form_html_erb__838826376_68516916' 
app/views/complaints/new.html.erb:3:in `_app_views_complaints_new_html_erb__529765002_56812308' 
app/controllers/complaints_controller.rb:150:in `block (2 levels) in create' 
app/controllers/complaints_controller.rb:135:in `create' 

_form.html.erb的错误(这里我有条件代码)

<strong>Originator:</strong><br> 

      <!-- Below will show the user name. If it is not a new complaint, we pull the user name from the complaint table 
      Otherwise, we get the name of the currently logged in user. --> 

      <% if action_name != "new" then %> 
       <%= @user.name %> 
      <% else %> 
       <%= @current_user.name %> 
        <%= f.hidden_field(:user_id, :value => @current_user.id) %> 
      <% end %> 


     </td> 

第27行是<%= @user.name %>我认为正在发生的事情是,验证失败后重装不再是“新”的动作。我怎样才能解决这个问题?

validates_presence_of :status 
    validates_presence_of :sales_order 
    validates_presence_of :product_name 
    validates_presence_of :coater_roll_number 
    validates_presence_of :coater_work_order 
    validates_presence_of :slitter_disposition 
    validates_presence_of :length 
    validates_presence_of :measure 
    validates_presence_of :disposition 
    validates_presence_of :reason_for_complaint 
    validates_presence_of :customer 

我认为正在发生的事情是,当窗体失败验证后重新加载,它不再是“新”的控制器动作。

+1

你在哪里设置'@ user'?确保它填充了一个值。 –

回答

1
undefined method `name' for nil:NilClass 

此错误只是意味着你的@usernil,这就是为什么它的失败上<%= @user.name %>。确保您的@user有价值,而不是nil。然后,它会工作。

您还可以尝试使用try这样的:<%= @user.try(:name) %>。这样,当@user为零时,程序不会崩溃。但是,最好的方法是找出为什么@user是零,并解决这个问题。

0

我发现当验证失败时,操作从NEW切换到CREATE。下面的代码将显示NEW和CREATE操作的@ current_user.name和编辑操作的表中的@ user.name。

<% if action_name != "new" && action_name != "create" then %> 
     <%= @user.name %> 
    <% else %> 
     <%= @current_user.name %> 
      <%= f.hidden_field(:user_id, :value => @current_user.id) %> 
    <% end %>