如何在类属性()结果中显示has_one关联模型?

时间:2013-02-15 16:14:56

标签: ruby-on-rails associations nested-attributes rails-activerecord has-one

Person has_one Brain,我希望brain显示在 attributes()返回的哈希中{ {1}}?如果是这样,如何实现这一目标?

Rails控制台输出:

Person

这两个模型是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} Person

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的属性中,因为Brain表格中有brains列。 person_id表不需要这样的列。

2 个答案:

答案 0 :(得分:0)

不确定列出属性之间的关联是个好主意,但是你可以获得这样的关联名称:

association_names = self.class.reflect_on_all_associations.map(&:name)

请参阅doc on reflections

答案 1 :(得分:0)

它没有显示大脑的属性,因为如果你看人的sql表..没有“脑”的字段..但在脑表中有person_id。

来自Viktor的关于如何反思关联的好建议!