2011-07-28 99 views
0

我有一個has_many父母的用戶模型。 我希望那個用戶模型有一個父親和一個母親。has_many with two has_one's

所以我的課家長belongs_to的用戶

目前我有

class User < ActiveRecord::Base 
    has_many :parents 

    has_one :father, :class_name => 'Parent', :foreign_key => 'user_id', :conditions => {:type => 'male'} 
    has_one :mother, :class_name => 'Parent', :foreign_key => 'user_id', :conditions => {:type => 'female'} 
end 

class Parent < ActiveRecord::Base 
    belongs_to :user 
end 

的問題是在我的控制器。

... 
def edit 
    @user = User.find(params[:id]) 
    @user.mother = Parent.new(:type => 'female') 
    @user.father = Parent.new(:type => 'male') 
... 

當我進入編輯,創建並拋出2位家長到數據庫,甚至無需在形式改變任何東西。例如,當我點擊用戶編輯時,我會進入編輯頁面。當我查看數據庫時,它們已經創建。

我的形式看起來像這樣:

= form_for @user do |f| 
    = f.fields_for :father do |father_form| 
    etc... 
    = f.fields_for :mother do |mother_form| 
    etc... 

我試着做一些單獨的這在我的控制線:

... 
@user.parents.build(:type => 'male') 
@user.parents.build(:type => 'female') 
... 

但是形式不出來。

任何幫助將不勝感激。

+0

爲什麼用戶有很多父母,但隨後他們被限制在單一的母親和父親?你期望他們還有什麼其他類型的父母?也許你甚至可能甚至沒有has_many:父母會開始簡化事情。 – MrDanA

+0

這只是描繪我試圖達到的模型。 – nbucciarelli

回答

3

嘗試在你的動作中使用的

@user.build_father(:type => 'male') 
@user.build_mother(:type => 'female') 

代替

@user.mother = Parent.new(:type => 'female') 
@user.father = Parent.new(:type => 'male') 

+0

這工作。除非在父母的數據元素上輸入值,否則有什麼方法可以阻止他們進入數據庫? – nbucciarelli

+1

是的,你可以通過在'accepting_nested_attributes_for:father'和'accep_nested_attributes_for:mother'中指定選項:reject_if來實現。檢查手冊在這裏:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for – Hck

+0

太棒了。非常感謝! – nbucciarelli

相關問題