views:

398

answers:

1

My comprehension of RoR is sadly lacking. I have three one-to-one relationships that I want to maintain in one view. I have the following models:

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

An Ood would have either an entry in the Female_Trait table or Male_Trait table, but not both. My efforts to tweak the scaffolded new/create edit/update definitions in my OodController have not succeeded. Here is an example of my faulty logic in 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

What concept am I missing?

+1  A: 

Why not use a polymorphic relationship that points to either Female_Trait or 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
epochwolf