【问题标题】:change name of attribute for has_and_belongs_to_many更改 has_and_belongs_to_many 的属性名称
【发布时间】:2017-01-12 20:40:22
【问题描述】:

是否可以更改 has_and_belongs_to_many 关联的属性名称?像

  class User
    has_and_belongs_to_many :users, as: :friends

让 User.friends 返回其他用户而不是 User.users?

【问题讨论】:

  • 您的连接表是什么样的? user_id, friend_id?

标签: ruby-on-rails rails-activerecord


【解决方案1】:

你可以的

has_and_belongs_to_many :friends, class_name: 'User'

您可能需要指定连接表,具体取决于您的设置

has_and_belongs_to_many :friends, class_name: 'User', join_table: '...'

可以在这里阅读更多关于这一切的信息has_and_belongs_to_many

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 2017-06-24
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2017-07-28
    相关资源
    最近更新 更多