2017-02-22 31 views
0

尝试实现电话号码检查器。它由用户输入电话号码,提交表格和检查我的数据库中的电话号码记录列表并查看它是否存在组成。我想发送不同的AJAX响应,具体取决于用户输入是否存在于数据库中。使用Rails从表单中检索值(phone_number)并检查它是否存在于数据库中。如果值存在,发送不同的ajax响应

我已经让ajax回复了一条消息,但是当我输入数据库中存在的一个数字时(例如07780319014),我收到了电话号码未找到的响应。

下面

实现的代码:

应用/视图/电话/ index.html.erb

<%= form_for :phone, url: phones_path, remote: true, html: { id: 'phone-number-form'} do |f| %> 
    <div id="phone-number-found"></div> 
    <div id="phone-number-not-found"></div> 
    <div id="phone-number-error"></div> 
    <%= f.text_field :phone_number %> 
    <%= submit_tag("Check") %> 
<% end %> 

应用程序/控制器/ phones_controller.rb

class PhonesController < ApplicationController 
    def create 
    @phone_number = Phone.where('phone_number = ?', params[:phone_number]) 
    if @phone_number.exists? 
     render 'phone-found' 

    elsif @phone_number.blank? 
     render 'phone-not-found' 

    else 
     render 'errors' 
    end 
    end 

    private 

    def phone_params 
    params.require(:phone).permit(
     :phone_number 
    ) 
    end 
end 

应用/视图/电话/ phone-found.js.erb

$('#phone-number-found').html('Working!'); 
$('#phone-number-not-found').html(''); 
$('#phone-number-error').html(''); 

应用程序/视图/电话/手机 - 不found.js.erb

$('#phone-number-found').html(''); 
$('#phone-number-not-found').html('Working!'); 
$('#phone-number-error').html(''); 

应用程序/视图/手机/ error.js.erb

$('#phone-number-found').html(''); 
$('#phone-number-not-found').html(''); 
$('#phone-number-error').html('Working!'); 

的config/routes.rb中

resources :phones, path: '4g-promo' 

如果有人能解决我的问题,将不胜感激。谢谢!

+0

告诉我它是否工作? –

+0

尝试'phone_number LIKE?',params [:phone_number] – jithya

+0

Nah仍然得到手机未找到的答复,试图@jith –

回答

0

您正在PARAMS出一个错误的方式

错误的方式

@phone_number = Phone.where('phone_number = ?', params[:phone_number]) 

正道

@phone_number = Phone.where('phone_number = ?', params[:phone][:phone_number]) 
+0

感谢您的回复@Aniket Shivam Tiwari不幸的是,一起打破了这一切:/我认为它是因为我的phone_number和sim_number字段在db是字符串 db/schema.rb 'create_table“phones”,force::cascade do | t | t.string“PHONE_NUMBER” t.string“SIM_NUMBER” 结束 ' 我将其更改为整数,(这应该是真的) 我在控制台得到的错误是500错误:” t将nil转换为整数 –

+0

你在params [:phone_number]中得到了什么显示在控制台上。还在控制台上做了params [:phone_number] .class并共享你的结果 –

+0

所以你在params [:phone_number]中得到了零。所以你需要检查它为什么没有得到零 –

0

你的表单数据都应该params[:phone]哈希中发现,

所以如果你想要一个精确的匹配,那么你可以这样做:

@phone_number = Phone.where(phone_number: params[:phone][:phone_number]) 

这将返回一个ActiveRecord::Relation(例如,空数组或火柴的阵列),或: -

@phone_number = Phone.find_by(phone_number: params[:phone][:phone_number] 

这将返回的记录或nil

但是,知道最终用户时,他们将以不同的方式格式化他们的电话号码,例如,间距,破折号等等,所以它不一定会完全匹配。

在上述两个示例中,您也可能想要使用phone_params而不是params[:phone]

相关问题