2013-03-20 104 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