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

我使用this comment作为指南进行了分类。我设置的类别为我的路线的资源,并用它来查询具体Product实例:创建ActiveRecord父实例与特定子实例的关系

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

回答:

我觉得这是你的主要问题:

哪有我查询具有特定类别的产品?

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

退房此链接了解更多信息上预装协会:http://blog.arkency.com/2013/12/rails4-preloading/

以上是 创建ActiveRecord父实例与特定子实例的关系 的全部内容, 来源链接: utcz.com/qa/257933.html

回到顶部