2016-01-25 24 views
0

這是我的第一個ror應用程序。 我有主頁:home.html.erb 我有形式那裏。Ror在db中查找記錄並將其顯示給用戶

<%= form_for(@lead ,:html => {:class => 'check_form'}) do |f| %> 

     <%= f.text_field :phone, placeholder: 'phone' %> 
    <%= f.submit "Check car status", class: "btn btn-large btn-primary" %> 
    <% end %> 

背景故事:一個客戶(我叫他主管可以輸入自己的電話號碼,並檢查它現在正在修理自己的汽車的狀態)

眼下這種觀點home.html.erbstatic_pages_controller

服務
class StaticPagesController < ApplicationController 
    def home 
    @lead = Lead.new() 
    end 

    def help 
    end 
    def about 
    end 
    def contact 
    end 
end 

我也LeadsController

class LeadsController < ApplicationController 
*some code* 

    def create 
    @lead = Lead.new(lead_params) 
    if @lead.save 
     #sign_in @lead 
     flash[:success] = "Request successfully created!" 
     redirect_to @lead 
    else 
     render 'new' 
    end 
    end 

* some code 
end 

當用戶輸入他的電話號碼以查找帶有相同電話號碼的數據庫中的潛在客戶並向用戶顯示修復狀態時,我想要執行的操作。

所以回到我的問題: 我知道如何找到像這樣的電話號碼Lead.find(params[:id]) 但是在哪裏寫這段代碼?我需要通過電話找到主持人,然後將其打印到屏幕上。我怎樣才能做到這一點?

+0

LeadController的show方法應該將查找委託給ActiveRecord類,您可以在該類中擁有一個名爲'find_by_phone_number'的方法(或者更好的範圍)。 –

+0

這裏的客戶(即鉛)是否已經在數據庫中創建? – Pavan

+0

@Pavan是的,它已經創建 – user2950593

回答

1

我想,當用戶輸入自己的電話號碼在 數據庫具有相同的電話號碼找到鉛和顯示修復狀態到用戶做什麼。

當前您的表單服務錯誤。這需要具有GET請求的表單。我將宣佈自定義route像下面

get :check_lead_car_status, to: 'static_pages#check_lead_car_status', as: 'check_lead_car_status' 

而在static_pages#check_lead_car_status

def check_lead_car_status 
    @lead = Lead.find_by(phone: params[:phone] 
end 

做IT和修改現有的格式如下面

<%= form_tag check_lead_car_status_path, :method => :get do %> 
    <%= text_field_tag :phone, placeholder: 'phone' %> 
    <%= submit_tag "Check car status", class: "btn btn-large btn-primary" %> 
<% end %> 

和頁check_lead_car_status.html.erb與下面的代碼

The Status of the Car is: <%= @lead.status %> 
+0

這是一個路由聲明中是未知的語法對我來說,我知道我只知道從像'比賽「/引線」,在教程中的一個! 'leads#index',via:'get'' – user2950593

+0

它是workking)))))))這真是太神奇了)再次感謝man! – user2950593

0

youre重定向到@lead這意味着應該是主控制器中的顯示路徑。這意味着你需要把這種邏輯在你的鉛控制器稱爲show

然後在視圖(views/leads/show.html.erb)方法,您可以訪問該變量


編輯:如果所有youre設法

要做的是通過不同的參數查詢,那麼你應該看看active record query interface。特別是部分1.1.5

Lead.find_by(phone: params[:phone])

+0

我已經有'def show @lead = Lead.find(params [:id]) end' – user2950593

+0

你可以檢查該變量的值嗎?你對應的'show'視圖將有權訪問它 – PhilVarg

+0

對不起,我不明白。檢查@lead的價值?就像我可以寫入放置@lead到控制檯,例如它會好嗎? – user2950593

相關問題