多对多通过关联在 Rails 应用程序中构建/创建属性 [英] Many-to-Many through association Build/Create properties in Rails app
问题描述
以下类相互关联(第一个没有教程的 rails 应用程序):
The following classes associate with each other (first rails app without a tutorial):
class Team < ActiveRecord::Base
has_many :team_users, :class_name => "TeamUser"
has_many :users, :through => :team_users
end
class TeamUser < ActiveRecord::Base
belongs_to :user
belongs_to :team
end
class User < ActiveRecord::Base
has_many :team_users, :class_name => "TeamUser"
has_many :teams, :through => :team_users
end
如果我有用户属性,在尝试执行以下操作时:
If I have user attribute, when trying to do the following:
u.teams.build(:name => "catsteam", :captain => true, :owner => :true)
Captain 和 Owner 是 TeamUser 类的属性.执行命令我得到以下内容:
Captain and Owner are properties of the TeamUser class. Executing the command I get the following:
u.teams.build(:name => "catsteam", :captain => true, :owner => :true)
ActiveRecord::UnknownAttributeError: unknown attribute: captain
...
from -e:1:in `load'
from -e:1:in `<main>'
附带说明,如果我获得用户,创建团队,然后创建团队用户,一切正常.我很困惑,已经搜索过但找不到任何东西.
On a side note if I get the user, create the team, then create the teamuser all works. I am so confused and have searched but cannot find anything.
谢谢.
推荐答案
u.teams
指的是 Team
实例.使用此命令,您正在构建 Team
实例,因此船长和所有者不被识别也就不足为奇了,因为它们是 TeamUser
的属性而不是用户.您应该分 2 个步骤执行此操作:
u.teams
refers to Team
instances. With this command you are building Team
instances so it is no surprise that captain and owner are not recognized as they are attributes of TeamUser
and not user.
You should do this in 2 steps:
team = Team.create
team_user = u.team_users.build(:team_id => team.id)
当然,如果您在 team_user
上遇到验证错误,您可能希望根据您的应用程序销毁您的团队.
Of course if you encounter a validation error on your team_user
you might want to destroy your team depending on your application.
这篇关于多对多通过关联在 Rails 应用程序中构建/创建属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!