not sure it is a good idea to list associations among attributes, but you can get association names like this:
association_names = self.class.reflect_on_all_associations.map(&:name)
Вопрос
Where Person
has_one
Brain
, should I expect brain
to show up in the hash returned by attributes()
for Person
? If so, how to make that happen?
Rails Console output:
1.9.3p327 :003 > Person.new.attributes
=> {"id"=>nil, "name"=>nil, "created_at"=>nil, "updated_at"=>nil}
1.9.3p327 :004 > Brain.new.attributes
=> {"id"=>nil, "weight_kg"=>nil, "created_at"=>nil, "updated_at"=>nil, "person_id"=>nil}
The two models are Person
and Brain
:
class Person < ActiveRecord::Base
has_one :brain
attr_accessible :name
attr_accessible :brain
attr_accessible :brain_attributes
accepts_nested_attributes_for :brain
end
class Brain < ActiveRecord::Base
belongs_to :person
attr_accessible :weight_kg
attr_accessible :person
attr_accessible :person_attributes
accepts_nested_attributes_for :person
end
person_id
shows up in the attributes for Brain
because the brains
table has a person_id
column. No such column need exist for the people
table.
Решение
not sure it is a good idea to list associations among attributes, but you can get association names like this:
association_names = self.class.reflect_on_all_associations.map(&:name)
Другие советы
It doesn't show attributes for brain in person because if you look at the sql table for person .. there is no field for "brain" .. but in the brain table there is person_id.
Good tip from Viktor on how to reflect on associations!