我有一个带有设计的用户模型,一个团队模型,一个播放器模型和一个培训师模型。我希望当用户注册时,其关联的团队将与相关的培训师和玩家一起创建。我已经设置了如下模型:
user.rb
has_one :team
has_one :trainer, :through => :team
has_many :players, :through => :team
accepts_nested_attributes_for :team, :allow_destroy => true
before_save :create_team
def create_team
@team = Team.new(params[:team])
@team.user = self
@team.save
end
team.rb
belongs_to :user
has_one :trainer
has_many :players
accepts_nested_attributes_for :trainer, :allow_destroy => true
accepts_nested_attributes_for :player, :allow_destroy => true
trainer.rb和player.rb
belongs_to :team
我没有添加create_trainer和create_player函数,因为我希望用户稍后在游戏中选择它们。所以在创建用户期间它们应该是空的。
但是注册过程会出现以下错误:
No association found for name `trainer'. Has it been defined yet?
并指的是:
accepts_nested_attributes_for :trainer, :allow_destroy => true
在team.rb中。如果没有验证Team模型中定义的Trainer是否存在,那么将Trainer项目尚未定义有什么问题?我尝试在Trainer模型中添加一些行,将属性设置为默认值,如:
morale.default => (5..12).to_a.sample
但它给出了进一步的错误,所以可能是错误的。非常感谢任何评论,特别是批评这里的基础的任何评论,因为我是一个菜鸟。
答案 0 :(得分:1)
一些事情:
不要在模型中使用实例变量。要在用户模型中访问团队,只需执行team
或self.team
。
请勿使用before_save
,因为每次保存用户时都不想创建团队。
您的create_team方法应为:
after_create :my_create_team
def my_create_team
create_team #create an empty team
end
但是,如果用户注册时新表单的数据已经存在于表单中,那么应该自动创建团队,因为您有accepts_nested_attributes_for :team
。
我将在这里的评论中回答你的一些问题:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one
因此,当您添加has_one :team
时,您现在可以访问所有这些方法(build_team,create_team,team = etc)
“空”,我的意思是,如果你只是在没有任何属性的情况下调用create_team
,它会创建一个“默认”团队:没有名称等。但它会链接到你的用户。
如果你想创建一个“空”团队,你可以这样做我想:
after_create :create_team
创建自己的方法只允许您传递默认参数。
但您可能已经向团队添加了验证,例如验证其名称的存在。
无论如何,由于您拥有accepts_nested_attributes_for :team, :allow_destroy => true
,如果您在注册表单中拥有用户团队所需的字段,则应自动创建团队。