2013-03-20 131 views
3

我真的很難理解如何去做一個嵌套窗體。用戶將登錄到應用程序,點擊「創建團隊」,此頁面將允許用戶輸入團隊名稱和團隊成員名單。 (有效地創建一個團隊成員名單)。Rails嵌套窗體屬性建設

  • 我有一個嵌套表格,其中包含fields_for成員資格,以創建成員資格。 See screenshot of form
  • 保存表格後,會員模型將運行Entrant.find_or_creates_by_name以創建參與者。
  • 我遇到的問題是,在創造我得到的錯誤信息:
    • 成員的團隊不能爲空

如何防止這種情況的發生,並允許用戶添加參賽者/確保會員創建正確?

道歉,如果這已經回答了,(似乎有通過與嵌套資源上的has_many許多議題,但沒有,我能找到處理我的具體問題(我可能/似乎不清楚)


我創建行動是目前標準的嵌套形式的行動如下:

我有以下型號:

用戶模型

class User < ActiveRecord::Base 
    has_many :teams 
end 

團隊模型

class Team < ActiveRecord::Base 
    belongs_to :user 
    has_many :memberships 
    has_many :entrants, :through => :memberships 

    attr_accessible :name, :team_type, :website, :memberships_attributes 
    accepts_nested_attributes_for :memberships, allow_destroy: true 
end 

成員型號

class Membership < ActiveRecord::Base 
    belongs_to :team 
    belongs_to :entrant 

    validates :team_id, presence: true 
    validates :entrant_id, presence: true 

    attr_accessor :entrant_name 
    attr_accessible :entrant_name 

    def entrant_name 
    entrant && entrant.name 
    end 

    def entrant_name=(name) 
    self.entrant = Entrant.find_or_create_by_name(name) unless name.blank? 
    end 

end 

參賽者模式 - 這實際上是團隊memberlistings的成員然而,當用戶進入他們可以指定一個團隊可能會改變的暱稱。

class Entrant < ActiveRecord::Base 
    attr_accessible :name 
    has_many :memberships 
    has_many :teams, :through => :memberships 
end 
+0

附加信息/文件以幫助解決這個問題:[表單視圖代碼](https://gist.github.com/digitaldawn/fc2edc87dbbe5889ffb9)| [開發日誌](https://gist.github.com/digitaldawn/c98dd9789094098258eb) – 2013-03-20 05:49:35

回答

0

我認爲它是一個驗證錯誤。嘗試刪除
驗證:entrant_id,presence:true
來自成員資格模型。

+0

當然,但是由於會員資格是參賽者和團隊之間的加入模式,會員資格不會存在嗎? – 2013-03-20 05:48:13

+2

當您使用accepting_nested_attributes_for時,保存記錄時會自動爲相應的父級和子級模型生成父級ID和子級ID。 – nilay 2013-03-20 05:51:21