문제

Answered it myself finally. I posted the answer. Thanks!

Quick question.

I'm wrapping up my RoR program and I'm trying to finish up user-proofing it. I'll give a quick run down of what I'm trying to do:

My program uses an HTML file that has a textfield for user input. The textfield input, customerId is supposed to be an integer. Anyways, I'm supposed to display a specific message if the input is invalid (validity based on specifications provided). I used this line to verify that the input customerId is an int:

<% if @customerId =~ /\D/ 
    render :action => 'invalid'
end %>

I'd like to put another if statement either in that or right after that.. that checks if the customer_Id value entered by the user is in the Customer table in the database.

Is there an easy way of doing this? Logically I think it would be something like:

<% if !Customer.find(@customer_Id)
   #customer not found message
end %>

This is the first project i've done using RoR and don't know of an easy implementation that Ruby provides for this. Thanks!

도움이 되었습니까?

해결책

To do this, I added some lines of code and instead of doing this in the view, I did it in the main controller. Here's the block that did it:

when  "cu" then  # customer data request
      # Verify that customer is in the customer table
      if Customer.exists?(@data)
         # exists, display custdisply.html.erb
               render :action => 'custdisplay'
      else
          # does not, display notfound.html.erb
               render :action => 'notfound'
      end

다른 팁

The Rails ActiveRecord library provides a lot of really nice validators which would seem appropriate in this case.

class Customer < ActiveRecord::Base
  validates_presence_of :name
end

However, in this case, a validator is not necessary. By default, when you call .find on the model class, if the ID is invalid, it will raise an ActiveRecord::RecordNotFound error and route to your public/404.html page:

class CustomersController < ApplicationController
  def show
    @customer = Customer.find(params[:id])
  end
end

If you try calling .find in a view script, it's too late because the routing has finished. You should be calling .find in your controller.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top