On Aug 25, 5:17 pm, Sandy <[email protected]> wrote:
> On Aug 25, 10:39 am, Ar Chron <[email protected]> wrote:
>
>
>
> > Sandy wrote:
> > > On Aug 25, 4:00 am, Colin Law <[email protected]> wrote:
> > >> >> Combining the lists and putting them in alphabetical order will show a
>
> > >> Colin
>
> > > Ok, Bob,
>
> > > The problem now seems to be that there is a Household model which
> > > contains two fields, name and sname, each of which is the full name
>
> > Yes, that would change the landscape a bit.  Sounds like Sandy's
> > solution has the right of it by using @households to build @sorted,
> > thereby replicating the household record for each resident.
>
> > --
> > Posted viahttp://www.ruby-forum.com/.
>
> I think that was the issue that Bob was trying to address, and I'm
> hoping it was due to his having inherited some legacy flat file
> database, and possilby not knowing how to normalize it, or being
> prevented from doing so by something else in the application which
> uses the households table.  Otherwise, the application cries out for
> relationships between a Person model (a "belongs_to :household"
> relationship) and the Household model (a "has_many :people"). While
> this does complicate, slightly, the addition of people to households,
> it would be a better way to approach the problem, and it would allow
> for more than two "authorized receivers" per household (although I
> have no idea of what the business rules are for his application, and
> they could be... 2 and only 2 per household).
>
> Next, @sorted, as defined in the households_controller, does not
> replicate the household record for each "authorized receiver" (I
> prefer that term, rather than "resident", because a household could
> include many residents, only two of whom are authorized to receive
> food from the food bank).  What @sorted does is to provide an array
> sorted by the names of the "authorized users" with the id of the
> relevant household record.  With that id, one can use Household.find
> to obtain the relevant household record and then obtain any other
> field from that record.  Of course, if any additional fields were
> needed in the view, they could be added to the hash in the @sorted
> array when it was created in the controller, thereby avoiding the need
> to do the lookups in the view and keeping the data access logic out of
> the view.
>
> While I did use @households in the households_controller, the only
> reason I did that was so that I could display both households and
> receivers in the same index.html.erb view, so that it was clear that
> the @sorted array was providing the "authorized users" in their sorted
> order with the id of the relevant household record.  Otherwise, better
> practice would be to have households be a local variable within the
> controller.
>
> Sandy


Thanks for the replies, Sandy. That was very close to what I needed..
The problem now is that I am using a text field with observe_field to
allow the list to be shrunk, as the beginning of the name is entered.
Then the household list is displayed with will_paginate. I can't seem
to fit the conditions to reduce the list and a call to paginate into
the code you provided. Below is my controller and view code.

By the way, the household class represents a household (novel, eh?).
It has HOH and spouse names, street address, mailing, zip, phone, and
income info.
There is a person model that only holds sex and birthday of each
person in the house. This is used for lists for christmas and to
report what age people and families used the foodbank.

class HouseholdsController < ApplicationController
  helper 'households'

  def admin
    @date = Time.now
  end

  def back
    $hidden = 0
    redirect_to(households_url)
  end

  def backup
    result = `~/foodshelf/script/backup`
    flash[:notice] = 'Backup completed'
    redirect_to(:action => 'index')
  #  debugger
  end

  def christmas
    #  debugger
    # children under 12
    @birthday = Date.today-12.years
    @f = Household.find(:all, :conditions => ["people.birthday
> :bday", {:bday => @birthday}], :joins => [:people])
    @family12 = @f.uniq.sort_by {|r| r.name_list}
    @test = Household.count :all, :group =>
'people.household_id', :joins => :people
    respond_to do |format|
      # format.xml { head :ok }
      format.pdf { send_data render_to_pdf( :action => 'christmas',
                                            :layout => 'pdf_report'),
                                            :filename =>
"Christmas_report_for_" + Date.today.strftime('%Y') }
    end
  end


  def copy
    result = `~/foodshelf/script/copy`
    flash[:notice] = 'Copy completed'
    redirect_to(:action => 'index')
  end

  def create
  #debugger
    @household = Household.new()
    @churches = Church.find(:all, :order => "name").map {|u| [u.name,
u.id]}
#debugger
    fix_dates
    if @household.update_attributes(params[:household])
      @v =
Visit.find_or_create_by_household_id_and_month_and_year(:household_id
=> params[:id], :month => @month, :year => @year)
      @v.update_attributes(params['visit'])
      flash[:notice] = 'Household was successfully saved.'
      redirect_to households_path
    else
      #debugger
      flash[:notice] = 'Create failed - look for a red field name'
      render(:action => :new)
    end
  end

  # DELETE /households/1
  # DELETE /households/1.xml
  def destroy
    # debugger
     @household = Household.find(params[:id])
     flash[:notice] = 'Household was deleted.'
     @household.destroy
  #   @delcmd = 'delete from visits where household_id = ' +
@household.id.to_s
   #  debugger
  #   Visit.connection.execute(@delcmd)
    #  flash[:notice] = "Successfully destroyed household."
    redirect_to(households_url)
  end

  def daysinmonth(mon)
        (Date.new(Time.now.year,12,31).to_date<<(12-mon)).day
  end

  # GET /households/1/edit
  def edit
   # debugger
    @today = Date.today
    @household = Household.find(params[:id])
    @churches = Church.find(:all, :order => "name").map {|u| [u.name,
u.id]}
    # debugger
    fix_dates
    @v =
Visit.find_or_create_by_household_id_and_month_and_year(:household_id
=> params[:id], :month => @month, :year => @year)
    @monthly = @v.monthly
 # debugger
  end

 def fix_dates
    # Get week of next Thursday
    # week is week of month
    @today = Date.today
    @day = @today.strftime('%d').to_i
    if (@day>8)
      @thisthurs =  Chronic.parse('last thursday')
    else
      @thisthurs =  Chronic.parse('next thursday')
    end
    @dayofthisthurs = @thisthurs.strftime('%d').to_i
    @monthofthisthurs = @thisthurs.strftime('%m').to_i
    @yearofthisthurs = @thisthurs.strftime('%Y').to_i
    @month = Date.today.mon()
    @daysinmonth = daysinmonth(@month)
    @year = @yearofthisthurs
    @dayoffirstthurs = @dayofthisthurs
    while @dayoffirstthurs>7
      @dayoffirstthurs -= 7
    end
  #debugger
    if (@day <= @dayoffirstthurs) # for getting correct week for fruit/
bread
      @week = 1
      @monthname = @today.strftime('%B')
    elsif (@day <= @dayoffirstthurs+7)
      @week = 2
      @monthname = @today.strftime('%B')
    elsif (@day <= @dayoffirstthurs+14)
      @week = 3
      @monthname = @today.strftime('%B')
   elsif (@day <= @dayoffirstthurs+21)
      @week = 4
      @monthname = @today.strftime('%B')
   elsif (@day <= @dayoffirstthurs+28 && @dayoffirstthurs+28 <=
daysinmonth(@month))
      @week = 5
      @monthname = @today.strftime('%B')
   else
      @week = 1
      @nextmonth = @today>>1
      @monthname = @nextmonth.strftime('%B')
    end
  end

  def get_person
    session[:person] ||= Person.new
  end

  def hidden
    $hidden = 1
    redirect_to(households_url)
  end

  def idreport
    @today = Date.today
   # @test2= Household.find(:all)
   # @test = @test2.sort_by{|c| [c.name_list, c.second_name_list] }
    @idstring = sprintf("select households.id, households.last_name,
households.first_name from households order by last_name, first_name")
    #  debugger
    @id = Household.find_by_sql(@idstring)
    respond_to do |format|
      # format.xml { head :ok }
      format.pdf { send_data render_to_pdf( :action => 'idreport',
                                            :layout => 'pdf_report'),
                                            :filename =>
"ID_List_for_" + @today.strftime('%m%d%%Y') }
    end
  end

  # GET /households
  # GET /households.xml
  def index
    conditions = ["last_name like ? ", "#{params[:search]}%"]
    if $hidden == 1 then
      @households = ArchivedHousehold.paginate :per_page => 16,
                                       :page => params[:page],
                                       :order => 'last_name',
                                       :conditions => conditions
    else
      @households = Household.paginate :per_page => 16,
                                       :page => params[:page],
                                       :order => 'last_name',
                                       :conditions => conditions
      $hidden = 0
    end
  end

  def monthly
#debugger
    @start = Date.new(params[:year].to_i, params[:month].to_i, 1)
    @end = @start>>1
    @newstring = sprintf("select last_name, first_name from households
where start_date >= '%10s' and start_date < '%10s' order by last_name,
first_name;",@start,@end)
  #  debugger
    @new = Household.find_by_sql(@newstring)
    @repeatstring = sprintf("select households.last_name,
households.first_name from households,visits where " +
                  "households.id=visits.household_id and
visits.month='%2d' and visits.year = '%4d' " +
                  "and visits.monthly = 1 and (households.start_date
>= '%10s' or households.start_date < '%10s') " +
                  "order by
households.last_name,households.first_name;", @start.month,
@start.year, @end, @start)
    @repeat = Household.find_by_sql(@repeatstring)
    @churches = Church.find(:all, :order => "name").map {|u| [u.name,
u.id]}

    respond_to do |format|
      # format.xml { head :ok }
      format.pdf { send_data render_to_pdf( :action => 'monthly',
                                            :layout => 'pdf_report'),
                                            :filename =>
"Monthly_report_for_" + @start.strftime('%B') + "_" +
@start.year.to_s }
    end
  end

   # GET /households/new
  # GET /households/new.xml
 def new
    @today = Date.today
    @lastthurs = Chronic.parse('last thursday of month')
    @dayoflastthurs = @lastthurs.strftime('%d').to_i
    @household = Household.new
    @household.people.build
    fix_dates
 end

 def print
   # debugger
    @churches = Church.find(:all, :order => "name").map {|u| [u.name,
u.id]}
#    @households = Household.find(:all, :order => "last_name,
first_name")
    @households = Household.find(278,279)
    # encrypt ??
    # if not encrypted, delete ?
    date=`date +%Y%m%d-%H:%M`
    respond_to do |format|
      format.pdf { send_data render_to_pdf( :action => 'print',
                                            :layout => 'pdf_report'),
                                            :filename =>
"Household_List_for_" + date }
    end
  end

  def putadmin
    debugger
  end

  def reset_links
    Household.find(:all).each { |h|
      if h.sfirst_name.nil? then
        h.sfirst_name=' '
      end
      if h.smiddle.nil? then
        h.smiddle=' '
      end
      if h.slast_name.nil? then
        h.slast_name=' '
      end
    h.save
    }
    redirect_to(households_url)
  end

  def restore
    Household.restore_all([ 'id = ?', params[:id] ])
    flash[:notice] = 'Household was restored.'
    $hidden = 0
    redirect_to(households_url)
  end

  def search
    conditions = ["last_name like ?", "#{params[:search]}%"]
    if $hidden == 0 then
      @households = Household.paginate :per_page => 16,
                                       :page => params[:page],
                                       :order => 'last_name',
                                       :conditions => conditions
    else
      @households = ArchivedHousehold.paginate :per_page => 16,
                                       :page => params[:page],
                                       :order => 'last_name',
                                       :conditions => conditions
    end
    render :partial=>"search", :layout=>false
  end

  # POST /households
  # POST /households.xml
  # PUT /households/1
  # PUT /households/1.xml
  def update
    @household = Household.find(params[:id])
    @churches = Church.find(:all, :order => "name").map {|u| [u.name,
u.id]}
    fix_dates
    @v =
Visit.find_or_create_by_household_id_and_month_and_year(:household_id
=> params[:id], :month => @month, :year => @year)
    if @week == 1 then
      @xweek = @v.week1
      @yweek = params[:visit][:week1].to_i
    elsif @week == 2 then
      @xweek = @v.week2
      @yweek = params[:visit][:week2].to_i
    elsif @week == 3 then
      @xweek = @v.week3
      @yweek = params[:visit][:week3].to_i
    elsif @week == 4 then
      @xweek = @v.week4
      @yweek = params[:visit][:week4].to_i
    elsif @week == 5 then
      @xweek = @v.week5
      @yweek = params[:visit][:week5].to_i
    end
    if @v.monthly != params[:visit][:monthly].to_i || @xweek != @yweek
      @today = Date.today
      @begin = Date.new(@today.year,7,1)
      if @household.start_date < @begin then
        @household.start_date = @today
      end
    end
    @v.update_attributes(params['visit'])
   # debugger
    if @household.update_attributes(params[:household])
      flash[:notice] = 'Household was successfully updated.'
      redirect_to households_path
    else
      flash[:notice] = 'Create failed - look for a red field name'
      @churches = Church.find(:all, :order => "name").map {|u|
[u.name, u.id]}
      render :action => "edit"
    end
  end

  def watch_address
 #   debugger
    if @match = Household.find_by_address(params[':address'])
      render :partial => "address_match"
    else
      render(:nothing=>true)
    end
  end

  def watch_church
    #  debugger
      if (params[':zip'] != "01540") && (params[':zip'] != "01537") &&
(params[':zip'] != "01611") then
      render :partial => "church_select"
    else
      render(:nothing=>true)
    end
  end
end


 
Index.html.erb

<h1>Index of Households</h1>
<%= text_field_tag 'search', params['search'], :autocomplete => "off"
%>
<%= observe_field 'search',
                                :frequency => 0.5,
                                :update => 'searchdiv',
                                :url => {:controller => 'households', :action 
=> 'search'},
                                :with => "'search=' + encodeURIComponent(value) 
" %>
<div id='searchdiv'>
         <%= render :partial=>"search" %>
</div>
<pre>
<% form_tag new_household_path do%>
<%= if $hidden == 0 then submit_tag "New household" end %>
<% end %>
<%= will_paginate @households %>

<%= link_to 'Admin', admin_path %>                      <%= if $hidden == 1 
then link_to
"Back", { :action => :back } end %>
</pre>
<%= javascript_tag('$("search").focus();') %>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to