0

I have an Account model that has many Entries, and I want to load the Account's entries only when it happens within a period. This period is different for each user session so my account.rb :

class Account < ActiveRecord::Base
  attr_accessible :code, :detail, :name
  attr_accessible :startDate, :endDate # not persisted in db
  has_many :entries, :order=>'date1,transref', :conditions => { :date1 => "#{@startDate}".."#{@endDate}" }

def startDate=(sd)
@startDate = sd
end

def startDate
@startDate
end

def endDate=(ed)
@endDate = ed
end

def endDate
@endDate
end

end

And my accounts_conttoller.rb:

def show
  @account = Account.find(params[:id])
  @account.startDate = '2012-02-01' #Actual value to be read from session[]
  @account.endDate = '2013-02-01' #Actual value to be read from session[]
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @account }
  end
end

When i invoke "show", @account.entries is empty and the SQL query used was:

SELECT ... WHERE entries.date1 BETWEEN '' and '' ... 

The startDate and endDate became empty. Where was my mistake?

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
cpliu338
  • 645
  • 1
  • 7
  • 20

2 Answers2

1

when you defining

has_many :entries, :order=>'date1,transref', 
  :conditions => { :date1 => "#{@startDate}".."#{@endDate}" }

your @-variables are class (or singleton) variables, and in def show they are instance variables

so you have to use smth like

@entries = self.entries.where( :date1 => @startDate..@endDate )

in your show method. And then, in view(s) access these entries using @entries instance variable

zed_0xff
  • 32,417
  • 7
  • 53
  • 72
1

You need to wrap the conditions in a proc so that they are evaluated dynamically, each time you call entries:

has_many :entries, :order=>'date1,transref', :conditions => proc { { :date1 => "#{@startDate}".."#{@endDate}" } }

I'd also recommend using the getter methods you defined (startDate and endDate), rather than directly accessing instance variables (generally considered bad practice):

has_many :entries, :order=>'date1,transref', :conditions => proc { { :date1 => "#{startDate}".."#{endDate}" } }

See also: Rails has_many with dynamic conditions

Community
  • 1
  • 1
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82