【问题标题】:Models associations belongs to and has模型协会属于并拥有
【发布时间】:2014-02-06 19:38:19
【问题描述】:

对于以下应该如何模型关联

User can purchase many Items
Items can be purchased by many users
Items have many categories

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord model associations


    【解决方案1】:

    Active Record Associations 文档似乎不言自明!

    您需要UserItem 之间的has_many...through 关系,以及ItemCategory 之间的has_many 关系。

    # app/models/user.rb
    class User < ActiveRecord::Base
      has_many :purchases
      has_many :items, through: :purchases
    end
    
    # app/models/item.rb
    class Item < ActiveRecord::Base
      has_many :purchases
      has_many :users, through: :purchases
      has_many :categories
    end
    
    # app/models/purchase.rb
    class Purchase < ActiveRecord::Base
      belongs_to :user
      belongs_to :item
    end
    
    # app/models/category.rb
    class Category < ActiveRecord::Base
      belongs_to :item
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多