我很难理解我对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中调整scaffolded new / create edit / update定义的努力没有成功。这是我在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
我错过了什么概念?
答案 0 :(得分:2)
为什么不使用指向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