【问题标题】:Basic Rails Question: One-to-One relationships基本 Rails 问题:一对一关系
【发布时间】:2009-04-21 22:00:26
【问题描述】:

遗憾的是,我对 RoR 的理解不足。我想在一个视图中保持三个一对一的关系。我有以下型号:

class  Ood< ActiveRecord::Base
  has_one :female_trait
  has_one :male_trait
end

class Female_Trait < ActiveRecord::Base
  belongs_to :ood
end

class Male_Trait < ActiveRecord::Base
  belongs_to :ood
end

Ood 可能在 Female_Trait 表或 Male_Trait 表中有一个条目,但不能同时在两者中都有。我在 OodController 中调整脚手架的新/创建编辑/更新定义的努力没有成功。这是我在 OodController 中的错误逻辑的示例:

def new
  @ood = Ood.new
  @female_trait = Female_trait.new   
  @male_trait = Male_trait.new
  ...
end

def create
  @ood = Ood.new(params[:ood])
  if !params[:female_trait][:trait1].blank? and !params[:female_trait[:trait2].blank?
    @female_trait = @ood.female_trait.build(params[:female_trait])
  if !params[:male_trait][:trait1].blank? and !params[:male_trait[:trait2].blank?
    @male_trait = @ood.male_trait.build(params[:male_trait])
  ...
end

我错过了什么概念?

【问题讨论】:

  • female_trait 和 male_trait 有相似的属性吗?
  • 不,我试图缩短我的示例代码,应该使用 trait1 到 trait4 而不是重用 trait1 和 trait2

标签: ruby-on-rails activerecord one-to-one


【解决方案1】:

为什么不使用指向 Female_Trait 或 Male_Trait 的多态关系?

class  Ood< ActiveRecord::Base
  belongs_to :trait, :polymorphic => true
end

class Female_Trait < ActiveRecord::Base
  has_one :oods, :as => :trait
end

class Male_Trait < ActiveRecord::Base
  has_one :oods, :as => :trait
end

【讨论】:

  • 如何在迁移中表达这一点?
  • 是吗?你可以展示一个如何创建Female_Trait对象的例子吗,我投票赞成:)
猜你喜欢
  • 2014-02-17
  • 2013-02-12
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2020-10-17
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多