如果某些内容与我的查询不匹配,需要帮助找出显示错误消息

时间:2015-03-26 17:52:16

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

问题是我有一个查询,查看我的emp_id文本框,一旦输入内容,就会搜索与emp_id相关联的信息,在我的另一个表中,它会搜索其被调用的ID ..如果emp_id与id匹配在我的视觉模型中,它将填充他们的名字。我想知道如果没有emp_id匹配我的视觉模型中的id,我怎么能显示错误....

这是我到目前为止所得到的但我一直没有方法错误......

这是错误

NoMethodError (undefined method `emp_matches' for #<Visual:0x00000005a4c8d8>):
  app/controllers/user_controller.rb:31:in `populate_form'

这是我的用户控制器。

class UserController < ApplicationController


def populate_form

  @visual = Visual.find_by_id(params[:emp_id])
  @emp_first_name = @visual.first_name

  if @visual.emp_matches(@emp_id).id
    flash[:notice] = "Emp Id found"


    render :json => {

        :emp_first_name => @emp_first_name

    }
  else
    flash[:error] = "Emp ID not found"
  end
end

这是我的视觉模型..

 class Visual < ActiveRecord::Base

 establish_connection :vtest

 self.table_name = 'employee'


 Visual.inheritance_column = 'inheritance_type'

 belongs_to :user

 def emp_matches?(x)
   (x.id.to_i == self.id.to_i ? true : false)
 end
end

这是我的观点..

<div class='row form-group'>
   <div class='col-xs-8 col-xs-offset-2 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-2 col-lg-offset-5 text-right'>
    <%= f.text_field :emp_id, tabindex: 1, id: 'emp_id', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>
  </div>
</div>

 <div class='row form-group'>
  <div class='col-xs-8 col-xs-offset-2 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4 col-lg-2 col-lg-offset-5 text-right'>
    <%= f.text_field :emp_first_name, tabindex: 1, id: 'emp_first_name', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>
   </div>
 </div>

我的桌子

视觉模型

      Table is called Employee 
        ID
        emp_first_name

用户模型

      Table is called User 


        emp_id           

修正了我的问号错误...

 def emp_matches(x)
   (x.id.to_i == self.id.to_i ? true : false)
 end
end

但我仍然没有遇到方法错误

 NoMethodError (undefined method `id' for nil:NilClass):
 app/models/visual.rb:18:in `emp_matches'
  app/controllers/user_controller.rb:31:in `populate_form'

1 个答案:

答案 0 :(得分:1)

我认为你已经过度复杂了,根据所提供的信息,我认为我们不需要关注user模型。你可以做这样的事情

def populate_form

   visual = Visual.find_by_id(params[:emp_id])
   if visual 
    render :json => {
        :emp_first_name => visual.first_name
    }
  else
    render :json => { :error => 'not found' }
  end
end

然后你的javascript可以做一些事情,如果它在json响应中找到emp_first_name,或者错误。我仍然不明白为什么需要emp_matches部分?