【问题标题】:has_many belongs_to and has_many through,How to solve this issue pls any one can help mehas_many belongs_to 和 has_many 通过,如何解决这个问题请任何人都可以帮助我
【发布时间】:2017-09-21 17:28:36
【问题描述】:
class User < ApplicationRecord
  has_many :groups
  has_many :memberships
  has_many :groups, through: :memberships
end
class users < ApplicationRecord
  belongs_to :group
  has_many :memberships
  has_many :groups, through: :memberships
end
class memberships < ApplicationRecord
   belongs_to :user
   belongs_to :group
end

人际关系有问题。

【问题讨论】:

    标签: jquery angular jquery-ui ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    你可以去rails的官网看看,对了解关联肯定会有帮助。它有很好的例子来澄清疑问。 http://guides.rubyonrails.org/association_basics.html

    【讨论】:

      【解决方案2】:

      试试这个...

      class User < ApplicationRecord
        has_many :memberships
        has_many :groups, through: :memberships
      end
      class Group < ApplicationRecord
        has_many :memberships
        has_many :groups, through: :memberships
      end
      class Membership < ApplicationRecord
         belongs_to :user
         belongs_to :group
      end
      

      删除 has_many :users 和 has_many :groups 以便您可以通过成员资格表访问用户组或用户组...

      User.find(1).groups
      

      或者...

      Group.find(1).users
      

      另外,一定要阅读答案https://stackoverflow.com/a/46350230/8503822中描述的文献

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多