【问题标题】:Rails - Determine what properties on an object are set by a setterRails - 确定对象的哪些属性由设置器设置
【发布时间】:2012-03-21 00:43:33
【问题描述】:

鉴于这个类:

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'}

【问题讨论】:

    标签: ruby-on-rails ruby metaprogramming


    【解决方案1】:

    也许你正在寻找changes

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

    【讨论】:

    • 更改已接近,但我不想更改我的原始对象。我想看看在不实际改变我的对象的情况下会改变什么。理想情况下,我根本不需要我的对象的实例。
    【解决方案2】:

    这是我目前的权宜之计,尽管我愿意分享:

    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
    

    这是内置在某个地方的rails中吗?

    【讨论】:

    • 这应该是对您的问题的修改,而不是答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2013-04-11
    • 2018-12-02
    • 2020-06-20
    • 2019-08-29
    相关资源
    最近更新 更多