同一型号上有多个 AND HABTM
我有两个模型“站点”和“用户”。当用户注册应用程序时,他们会选择所属的网站。因此,一个站点 has_many :users 和一个用户 own_to :site 。
app\models\site.rb
class Site < ActiveRecord::Base
has_many :users
end
app\models\user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
belongs_to :site
has_and_belongs_to_many :roles, :uniq => true
end
这确实反映了用户的主站点,我经常调用该关系来找出用户来自哪里,例如:
<%= user.lastname %>, <%= 用户名 %>来自站点:<%= user.site.name %> 翻译过来就是: 来自站点 GenericCo Operations 的 Smith、John
我想添加一个 habtm 关系,用户可以在其中支持许多站点,这样用户就可以从列出站点的复选框中选择他们支持的站点。
我熟悉 habtm 关系,因为我的用户拥有并属于许多角色。我之所以这样做是因为
has_and_belongs_to_many :roles, :uniq => true
我知道,如果我添加一个连接表并在我的模型上使用
has_and_belongs_to_many :sites ,
一切都会因为大量错误而变得疯狂。我将不胜感激任何有用的建议和代码提示。
I have two models Site and User. When a user registers with the app they choose a site to belong to. So a site has_many :users and a user belongs_to :site.
app\models\site.rb
class Site < ActiveRecord::Base
has_many :users
end
app\models\user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
belongs_to :site
has_and_belongs_to_many :roles, :uniq => true
end
This really reflects a user's home site and I often call the relationship to find out where the user is from, for instance:
<%= user.lastname %>, <%= user.firstname %> from Site: <%= user.site.name %>
which translates to:
Smith, John from Site: GenericCo Operations
I would like to add a habtm relationship where users can SUPPORT many sites, so a user would be able to choose which sites they support from check boxes listing the sites.
I am familiar with the habtm relationship because my users have and belong to many roles. I established this as
has_and_belongs_to_many :roles, :uniq => true
I know for a fact that if I add a join table and use
has_and_belongs_to_many :sites
on my model everything will go crazy with tons of errors. I would appreciate any helpful advice and code hints.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
habtm 的第一个参数是您将调用以获取集合的方法的名称。它可以是您想要的任何内容,只要您使用 :class_name 指定模型类即可,
具体取决于您在数据库中命名事物的方式,您可能还需要指定 :join_table、:foreign_key 或 :association_foreign_key。查看 http://apidock.com/rails/ActiveRecord/Associations 的选项部分/ClassMethods/has_and_belongs_to_many 了解更多信息。
The first argument to habtm is the name of the method you'll call to get the collection. It can be anything you want, so long as you specify the model class with :class_name
Depending on how you name things in your database, you might also need to specify :join_table, :foreign_key, or :association_foreign_key. Take a look at the Options section of http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many for more info.