【问题标题】:Source of the New and Create Methods in Rails ActiveRecord while using Associations使用关联时 Rails ActiveRecord 中的 New 和 Create 方法的来源
【发布时间】:2013-05-13 06:45:15
【问题描述】:

我想知道在 Rails 中使用关联时,New 和 Create 方法的来源(即定义类或模块)是什么。

例如,Rails 指南的“关联”部分提供了这种情况:

class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :destroy
end

class Order < ActiveRecord::Base
  belongs_to :customer
end

然后在控制台输入这个命令:

@order = @customer.orders.create(:order_date => Time.now)

(Rails 指南部分的链接:http://guides.rubyonrails.org/association_basics.html

但是当我输入这个时:

@customer.orders.method(:create)

我得到错误:

undefined method `create' for class `Array'

【问题讨论】:

标签: ruby-on-rails ruby associations models


【解决方案1】:

您应该在这里查看collection_proxy.rb - https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/collection_proxy.rb
第 204 行开始看,它充分解释了 Rails 如何神奇地在关联中使用 buildcreate 等方法。

它们是Associations 模块和CollectionProxy 类的一部分。

编辑:
由于 Ruby 中的metaprogramming 功能,这些动态方法中的大多数都到达了 Rails。 @customer.orders 也是 AssociationsCollectionProxy 是包含在此模块中的类,因此提供了这些实例方法。

@foo = @customer.orders
@foo.included_modules 
#=> List of all `ActiveRecord` and `ActiveModel` modules, it includes.
@foo.include? ActiveRecord::Associations
#=> True

因此,@foo 获得了诸如 buildcreate 之类的方法的荣誉,它们存在于那里,与另一个 Array 对象不同。

【讨论】:

  • 你能多解释一下魔法是如何发生的吗?在阅读 Rails 源代码时,我仍然需要一些练习,因此该资源对我的帮助不如对其他人的帮助大。当 Array 类似乎没有混合其中任何一种方法时,我仍然对如何在 Array 的实例上调用 new 或 create 感到困惑。
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2021-11-30
  • 2017-10-10
  • 1970-01-01
相关资源
最近更新 更多