如何Rails的ActiveRecord的关系佣工允许的方法,如`user.groups.new`? [英] How do Rails ActiveRecord relationship helpers allow methods such as `user.groups.new`?

查看:142
本文介绍了如何Rails的ActiveRecord的关系佣工允许的方法,如`user.groups.new`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails中,我创建了一个模型,检索用户LDAP数据库而不是ActiveRecord的。现在,我试图用基于LDAP的模型集成我的ActiveRecord模型,所以我写了模仿一些常见的ActiveRecord的方法在我的模型方法。

In Rails, I have created a Model that retrieves users from an LDAP database rather than from ActiveRecord. Now I am attempting to integrate my ActiveRecord models with the LDAP-based models, so I am writing methods in my models that emulate some common ActiveRecord methods.

一个我试图仿效的方法是一种通常由的has_many通过ActiveRecord的关系创建。在ActiveRecord的,这种关系将允许以下内容:

One of the methods I am trying to emulate is one that is normally created by the has_many through relationship on ActiveRecord. In ActiveRecord, this relationship would allow the following:

user = User.first
groups = user.groups # == Array of Groups
groups << Group.create(name: "Test") # How does Rails allow this?

究竟如何Rails的允许这样做?我试着动态分配方法由user.groups返回的数组实例,但似乎没有任何办法,使那些用户记录知道的阵列从创建的方法。 (因此,他们可以指定 USER_ID 上的新关系的记录。)我在想什么?

How exactly does Rails allow this? I've tried dynamically assigning methods to the array instance returned by user.groups, but there doesn't seem to be any way to make those methods aware of which user record the array was created from. (So they can assign user_id on the new relationship record.) What am I missing?

推荐答案

虽然 user.groups 似乎是组阵列,它实际上是一个完全独立的类 - Rails的内部类,你平时不很了解称为关联代理。代理响应像&LT方法;&LT; 创建等通过将请求代理到目标类,然后适当地设置关联。

Though user.groups appears to be an array of groups, it's actually an entirely separate class -- a Rails internal class that you usually don't know much about called an association proxy. The proxy responds to methods like <<, create, new and so on by proxying requests to the target class and then setting the association appropriately.

如果你想类似的功能,你必须实现自己的类型的代理协会。这样做将是pretty的复杂,但是这可能让你开始。

If you want similar functionality you'll have to implement your own kind of proxy associations. Doing so will be pretty complicated, but this might get you started.

module LDAP
  class Association
    attr_accessor :source, :target

    def initialize(source, target)
      @source = source
      @target = target
    end

    def <<(obj)
      @source.group_ids = [group_ids + obj].flatten.uniq
      @source.save
    end

  end
end

class User
  def groups
    LDAP::Association.new(self, Group)
  end
end

这甚至不是特别接近的ActiveRecord如何实现关联代理。然而,这是比的ActiveRecord的溶液要简单一些,并应足以重复一些基本的ActiveRecord功能。

This is not even particularly close to how ActiveRecord implements association proxies. However, this is quite a bit simpler than ActiveRecord's solution and should be enough to duplicate some basic ActiveRecord functionality.

这篇关于如何Rails的ActiveRecord的关系佣工允许的方法,如`user.groups.new`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆