【问题标题】:How to make a has_one associated model show up in class attributes() result?如何使 has_one 关联模型显示在类 attributes() 结果中?
【发布时间】:2013-02-15 16:14:56
【问题描述】:

Personhas_oneBrain,我应该期望brain 出现在由attributes()Person 返回的散列中吗?如果是这样,如何做到这一点?

Rails 控制台输出:

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} 

两个型号分别是PersonBrain

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 列。 people 表不需要这样的列。

【问题讨论】:

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


    【解决方案1】:

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

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

    doc on reflections

    【讨论】:

      【解决方案2】:

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

      维克多关于如何反思联想的好建议!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多