【问题标题】:Trying to get an value from a DataMapper join table and association尝试从 DataMapper 连接表和关联中获取值
【发布时间】:2010-10-05 03:46:44
【问题描述】:

我有 3 个类 - Mix、MixClip 和 Clip。

class Mix

  include DataMapper::Resource

  property :id, Serial
  # <removed other code for brevity>

  has n, :mix_clips
  has n, :clips, :through => :mix_clips

end

class MixClip
  include DataMapper::Resource

  property :id, Serial
  property :order, Integer      

  belongs_to :mix
  belongs_to :clip
end

class Clip
  include DataMapper::Resource

  property :id, Serial
  property :title,            String    
  property :description,      Text

  has n, :mix_clips
  has n, :mixes, :through => :mix_clips
end

MixClip 加入了 Mix/Clip 表,并包含一个额外的属性来描述剪辑(顺序)。我想知道是否有可能拥有一个剪辑对象并能够在加载它的上下文中引用当前剪辑。

假设我像这样加载一个 Mix 和一个 Clip:

mix = Mix.first
clip = mix.clips.first

有没有办法获取与该特定剪辑关联的 MixClip?

clip.mix_clip.order

它是通过表之间的连接加载的,所以我认为有办法做到这一点。

我知道我可以得到所有的 mix->mix->clips-> 并向下钻取,但我想知道我是否能够回到更高的水平......这会更简单。

对于那些想知道的人,我正在尝试使用它,因为 dm-serializer 在返回 json/xml 时不完全支持嵌套关联,我希望能够只定义一个返回数据的方法。

谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 datamapper


    【解决方案1】:

    在不更改任何代码的情况下,您应该能够做到:

    mix_clip = clip.mix_clips.first(:mix => mix, :clip => clip)
    

    获取与您的特定 mixclip 资源关联的加入记录。

    目前,DM 中存在一个错误,使得在没有任何额外措施的情况下执行以下操作有点不可靠:

    mix_clip = clip.mix_clips.get(mix.id, clip.id)
    

    这是因为 DM 忘记了定义关系的顺序,因此目前无法可靠地知道.get 方法应该接受主键组件的顺序。

    您可以通过在连接模型中显式定义外键属性来解决此问题,如下所示(请注意,您仍然必须显式声明关系):

    class MixClip
      include DataMapper::Resource
    
      property :id,      Serial
      property :order,   Integer      
    
      property :mix_id,  Integer, :key => true
      property :clip_id, Integer, :key => true
    
      belongs_to :mix
      belongs_to :clip
    end
    

    这将确保 DM 知道 .get 接受主键为 (mix_id, clip_id),因此您现在可以调用

    mix_clip = clip.mix_clips.get(mix.id, clip.id)
    

    想要这样做的一个原因是对 .get 的调用会考虑身份映射,根据您的访问特征,这可能会产生更好的性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 2013-10-17
      • 2012-09-02
      相关资源
      最近更新 更多