Rails - определяет, какие свойства объекта устанавливаются установщиком - PullRequest
0 голосов
/ 21 марта 2012

Учитывая этот класс:

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

Я знаю, что когда я устанавливаю ассоциацию1, она устанавливает ассоциацию1_id в ID объекта 1

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

Я знаю, что когда я устанавливаю ассоциацию2,он устанавливает 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 ]

2 голосов
/ 21 марта 2012

Возможно, вы ищете changes:

person = Person.new
person.changes # => {}
person.name = 'bob'
person.changes # => { 'name' => [nil, 'bob'] }
0 голосов
/ 21 марта 2012

Это решение для ограничения пробелов, которое я имею на данный момент, хотя я бы поделился:

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

Это где-то встроено в рельсы?

...