Ruby on rails 3 ActiveRecord有许多用户定义的条件

Ruby on rails 3 ActiveRecord有许多用户定义的条件,ruby-on-rails-3,associations,Ruby On Rails 3,Associations,我有一个帐户模型,它有许多条目,我只想在一段时间内加载帐户条目。此时间段对于每个用户会话都不同,因此我的帐户.rb: class Account < ActiveRecord::Base attr_accessible :code, :detail, :name attr_accessible :startDate, :endDate # not persisted in db has_many :entries, :order=>'date1,transref', :c

我有一个帐户模型,它有许多条目,我只想在一段时间内加载帐户条目。此时间段对于每个用户会话都不同,因此我的
帐户.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
调用
“show”
时,
@account.entries
为空,使用的SQL查询为:

SELECT ... WHERE entries.date1 BETWEEN '' and '' ... 
startDate
endDate
变为空。我的错误在哪里?

当你定义

has_many :entries, :order=>'date1,transref', 
  :conditions => { :date1 => "#{@startDate}".."#{@endDate}" }
您的
@
-变量是类(或单例)变量,在
def show
中,它们是实例变量

所以你必须像这样使用smth

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

在您的show方法中。然后,在视图中,使用
@entries
实例变量访问这些条目

您需要将条件包装在
过程中
,以便在每次调用
条目
时对其进行动态评估:

has_many :entries, :order=>'date1,transref', :conditions => proc { { :date1 => "#{@startDate}".."#{@endDate}" } }
我还建议使用您定义的getter方法(
startDate
endDate
),而不是直接访问实例变量(通常认为是不好的做法):

另见:

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