Rails - 确定setter设置对象的哪些属性

时间:2012-03-21 00:43:34

标签: ruby-on-rails ruby metaprogramming

鉴于此课程:

class MyModel < ActiveRecord::Base
  belongs_to :association1
  belongs_to :association2, :polymorphic => true
end

我知道当我设置association1时,它会将association1_id设置为对象1的ID

m = MyModel.new
m.association1 = object1
#<MyModel id: nil, association1_id: 1, association2_id: nil, association2_type: nil>

我知道当我设置association2时,它会设置association2_id AND association2_type

m.association2 = object2
#<MyModel id: nil, association1_id: 1, association2_id: 2, association2_type: 'ClassType'>

我的问题是:

是否有一个函数可以很容易地告诉我以散列形式在对象上设置了哪些信息?

MyModel.magic_function(:association1, object1)
# returns {:association1_id => 1}
MyModel.magic_function(:association2, object2)
# returns {:association2_id => 2, :association2_type => 'ClassType'}

2 个答案:

答案 0 :(得分:2)

也许您正在寻找changes

person = Person.new
person.changes # => {}
person.name = 'bob'
person.changes # => { 'name' => [nil, 'bob'] }

答案 1 :(得分:0)

这是我现在的止损解决方案,虽然我会分享:

def self.magic_method(association, object)
  instance = self.new
  instance.send(association, object)
  h = Hash.new
  instance.changes.each do |k,v|
    h[k] = v[1]
  end
  h
end

这是在某个地方构建的吗?