Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, April 07, 2010

ruby script/generate scaffold client_workout client_name:string trainer:string duration_mins:integer date_of_workout:date paid_amount:decimal

rake db:migrate

Problem is that the scaffolding app doesn’t do exactly what we want.

image

what we want is just the listing for Lenny Goldberg ie a filter.

Creating a Form with no Model

instead of form_for

<% form_for(@ad,:url=>{:action=>'update'}) do |f| %>
  <p><b>Name</b><br /><%= f.text_field :name %></p>
  <p><b>Description</b><br /><%= f.text_area :description %></p>
  <p><b>Price</b><br /><%= f.text_field :price %></p>
  <p><b>Seller</b><br /><%= f.text_field :seller_id %></p>
  <p><b>Email</b><br /><%= f.text_field :email %></p>
  <p><b>Img url</b><br /><%= f.text_field :img_url %></p>
  <p><%= f.submit "Update" %></p>
<% end %>

we use form_tag

<% form_tag "/client_workouts/find" do%>
      <%= text_field_tag :search_string%>
      <%= submit_tag "Search" %>
    <% end %>

 

image

image

by putting in dave into the search box, we can see it coming through in the controller by using puts to output to the console.

So we only need those records where client_name = the search string.

def find
      puts params[:search_string]
      @client_workouts = ClientWorkout.find_all_by_client_name(params[:search_string])
  end

The framework creates finders for each attribute.. eg find_all_by_client_name.

and I just wired up to a find.html.erb file.

image

however we want to search on trainer as well ie where client_name=”Lenny Goldbery” or trainer = “Lenny Goldberg”

@client_workouts = ClientWorkout.find(:all, :conditions=>["client_name = ? OR trainer = ?",
                          params[:search_string], params[:search_string]])

image

The crowd goes wild!  Can filter on client_name or trainer.

Validators

A number:

class ClientWorkout < ActiveRecord::Base
    validates_numericality_of :paid_amount
end

Mandatory:

class ClientWorkout < ActiveRecord::Base
    validates_numericality_of :paid_amount
    validates_presence_of :trainer
    validates_presence_of :client_name
end

image

 

Doing it on custom code:

class Ad < ActiveRecord::Base
  validates_presence_of :price
  validates_presence_of :name
end

def create
      @ad = Ad.new(params[:ad])
      if @ad.save
        redirect_to "/ads/#{@ad.id}"
      else
        render :template => "ads/new"
      end
  end

<% form_for(@ad,:url=>{:action=>'create'}) do |f| %>
    <%=f.error_messages%>

image