【问题标题】:Many-To-Many Association Query多对多关联查询
【发布时间】:2020-10-06 21:33:37
【问题描述】:

我有以下型号:

class Restaurant < ApplicationRecord
  has_one_attached :image
  has_many :categories, through: :restaurant_category
end

class Category < ApplicationRecord
  has_many :restaurants, through: :restaurant_category
end

class RestaurantCategory < ApplicationRecord
  belongs_to :restaurant
  belongs_to :category
end

我会一次性查询与餐厅相关的所有类别。像这样的东西:

a = Restaurant.find(1)
a.restaurant_category 

但我有:

NoMethodError (undefined method `restaurant_category' for #<Restaurant:0x00007f5214ad2240>)

我该如何解决?

【问题讨论】:

    标签: ruby-on-rails activerecord many-to-many associations


    【解决方案1】:

    这个:

    class Restaurant < ApplicationRecord
      has_one_attached :image
      has_many :categories, through: :restaurant_category
    end
    

    ... 应该是这样的:

    class Restaurant < ApplicationRecord
      has_one_attached :image
      has_many :restaurant_categories
      has_many :categories, through: :restaurant_categories
    end
    

    同样,这个:

    class Category < ApplicationRecord
      has_many :restaurants, through: :restaurant_category
    end
    

    ... 应该是这样的:

    class Category < ApplicationRecord
      has_many :restaurant_categories
      has_many :restaurants, through: :restaurant_categories
    end
    

    你会使用喜欢的:

    restaurant_categories = Restaurant.find(1).categories
    

    这一切都在Active Record Associations 指南的has_many :through 部分进行了解释。

    【讨论】:

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