创建ActiveRecord父实例与特定子实例的关系

时间:2016-04-29 04:04:09

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我使用this comment作为指南制作了类别。我在我的路由中将类别设置为资源,并使用它来查询特定的Product实例:

class CategoriesController < ApplicationController
  def show
    @category = Category.find(params[:id])
    @products = []

    products = Product.all

    products.each do |product|
      if product.categories.include?(@category)
        @products << product
      end
    end
  end
end

然后我在视图中迭代@products。这已经成为一个问题,因为我希望categories/showproducts/index共享一个视图,以便更加干净。 products/index仅使用<%= render @products %>,我无法通过render数组。

如何查询具有特定类别的产品?

我想到的伪代码:

class CategoriesController < ApplicationController
  def show
    @category = Category.find(params[:id])
    @products = Product.where(categories.include?(@category))
  end
end

评论中的类别设置:

class Category < ActiveRecord::Base
  acts_as_tree order: :name
  has_many :categoricals
  validates :name, uniqueness: { case_sensitive: false }, presence: true
end

class Categorical < ActiveRecord::Base
  belongs_to :category
  belongs_to :categorizable, polymorphic: true

  validates_presence_of :category, :categorizable
end

module Categorizable 
  extend ActiveSupport::Concern

  included do
    has_many :categoricals, as: :categorizable
    has_many :categories, through: :categoricals
  end

  def add_to_category(category)
    self.categoricals.create(category: category)
  end

  def remove_from_category(category)
    self.categoricals.find_by(category: category).maybe.destroy
  end

  module ClassMethods
  end
end

class Product < ActiveRecord::Base
  include Categorizable
end

p = Product.find(1000) # returns a product, Ferrari
c = Category.find_by(name: 'car') # returns the category car

p.add_to_category(c) # associate each other
p.categories # will return all the categories the product belongs to

1 个答案:

答案 0 :(得分:0)

我认为这是你的主要问题:

  

如何查询具有特定类别的产品?

Product.includes(:categories).where(categories: {id: params[:id]}).references(:categories)

有关预加载关联的更多信息,请查看此链接:http://blog.arkency.com/2013/12/rails4-preloading/