Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何通过集合表达:has“one association:,使用:condition to construct/select”来表示;“那一个?”;?_Ruby On Rails_Associations - Fatal编程技术网

Ruby on rails 如何通过集合表达:has“one association:,使用:condition to construct/select”来表示;“那一个?”;?

Ruby on rails 如何通过集合表达:has“one association:,使用:condition to construct/select”来表示;“那一个?”;?,ruby-on-rails,associations,Ruby On Rails,Associations,我有一些这样的模型(Rails3.2),A->B->C,来模拟一个管理者(A),他覆盖许多区域(B),每个区域都有许多地址(C)。其中一个地址是经理的主地址。我想不出将经理与其主要地址联系起来的最佳方式 class AreaManager < ActiveRecord::Base has_many :areas, :dependent=>:destroy has_many :addresses, :through=>:areas ... def primary_

我有一些这样的模型(Rails3.2),A->B->C,来模拟一个管理者(A),他覆盖许多区域(B),每个区域都有许多地址(C)。其中一个地址是经理的主地址。我想不出将经理与其主要地址联系起来的最佳方式

class AreaManager < ActiveRecord::Base
  has_many :areas, :dependent=>:destroy
  has_many :addresses, :through=>:areas
  ...
  def primary_address
    self.addresses.where(:primary=>true).first 
      # in fact, there can be only one
  end
end

class Area < ActiveRecord::Base
  belongs_to :area_manager
  has_many :addresses,:dependent=>:destroy
end

class Address < ActiveRecord::Base
  belongs_to :area
  attr_accessible :primary 
    # this is the manager's primary address (not the area's)
end
但我真正想要的是构造函数/设置器以及getter:

a = AreaManager.new
a.build_primary_address ...
我可以添加到以下区域:

has_one :primary_address, 
  :class_name=>'Address', 
  :conditions => {:primary=>true}
这让我可以

a1 = Area.new
a1.build_primary_address ... # instantiates an Address with primary = true
但当我尝试做一些类似于AreaManager的事情时,添加

has_one :primary_address, 
  :through=>:areas, 
  :source=>:address, 
  :conditions=>{:primary=>true}
然后说:

a = AreaManager.new
a.build_primary_address ... 
  # instead of creating an area and an address, it croaks

我得到一个ActiveRecord::HasOneThroughCanAssociateThroughCollection异常。我不知道正确的咒语可能是什么(或者是否有)。有没有什么好办法

由于rails都是关于以下约定和许多选项中的正确选择,我建议:

  • 不要对关联应用条件

  • 查找使用命名的
    范围

  • 请注意使用
    。其中
    (rails3)而不是
    条件
    (rails2)。有关更多信息,请参阅
    应用所有这些可能会对您的代码进行相当大的更改,您将得到不同的结果

a = AreaManager.new
a.build_primary_address ... 
  # instead of creating an area and an address, it croaks