Ruby on rails 如何从多个具有ActiveRecord关联的项目中获取最新的单个项目?

Ruby on rails 如何从多个具有ActiveRecord关联的项目中获取最新的单个项目?,ruby-on-rails,ruby,design-patterns,activerecord,Ruby On Rails,Ruby,Design Patterns,Activerecord,我的代码有一些问题。这可能是由于某些设计错误造成的。我试过几种方法。这里有两个 问题:我有一个1(贷款)-N(合同)关系。我想打电话给lending.current_contract,它将返回最后一份相关合同。 优化也是一个问题。我想调用:lending,:include=>:contracts,而不必对包含所有合同的合同数组中已经存在的合同使用单独的查询 糟糕的解决方案1: has_one :current_contract, :class_name => "Contract" 这不起

我的代码有一些问题。这可能是由于某些设计错误造成的。我试过几种方法。这里有两个

问题:我有一个
1(贷款)-N(合同)
关系。我想打电话给lending.current_contract,它将返回最后一份相关合同。 优化也是一个问题。我想调用
:lending,:include=>:contracts
,而不必对包含所有合同的合同数组中已经存在的合同使用单独的查询

糟糕的解决方案1:

has_one :current_contract, :class_name => "Contract"
这不起作用,因为每次我创建、更新或销毁时,它也必须更新父借出。这样做会让我一团糟。例如,在创建贷款时,它还会创建第一个合同。由于某种原因,在合同不起作用的情况下,对两种贷款来回使用回调

糟糕的解决方案2:

def current_contract
  return if contracts.relevant.empty?
  @current_contract = contracts.relevant.last
end
发送副本而不是引用。因此,
lending.current_contract.status=value
不起作用


是否有一些设计模式,我应该看看?还有一些例子吗?我看过一些github项目,但没有一个项目解决了类似的问题,因此我认为这是一个设计问题。

关联通常可以采用
:条件
散列,这很方便。(直到半小时前我需要它时,我才把它忘了)

会有帮助吗?比如:

has_one :current_contract, :class_name => "Contract", :conditions => ...
再看一点(确切地说是第364页):

…将引用最近创建的合同。当然,你可以有一个更合适的专栏


我希望我早一点看到这一点——我现在需要去修改一些代码……

关联通常可以使用
:conditions
散列,这很方便。(直到半小时前我需要它时,我才把它忘了)

会有帮助吗?比如:

has_one :current_contract, :class_name => "Contract", :conditions => ...
再看一点(确切地说是第364页):

…将引用最近创建的合同。当然,你可以有一个更合适的专栏


我希望我早一点看到这一点-我现在需要去修改一些代码…

所谓的“相关”,你是指最近的吗

class Lending < ActiveRecord::Base
  has_many :contract
  attr_reader :current_contract

  def initialize
   @current_contract = Contract.New
  end
  ...
end

class Contract < ActiveRecord::Base
  has_one :lending
  ...

  def before_delete
    # update lending to the most relevant contract
    # if this is the current_contract for parent lending
  end
end
classlending
所谓“相关”,是指最近的吗

class Lending < ActiveRecord::Base
  has_many :contract
  attr_reader :current_contract

  def initialize
   @current_contract = Contract.New
  end
  ...
end

class Contract < ActiveRecord::Base
  has_one :lending
  ...

  def before_delete
    # update lending to the most relevant contract
    # if this is the current_contract for parent lending
  end
end
classlending