我正在开发一款电子商务应用程序,我正在努力理解以下问题:
我通过awesome_nested_set插件实现了我的类别。如果我通过选择一个类别列出我的文章,一切都很好,但是对于某些链接,我想显示一个类别和其子类别的所有产品。
这里是控制器代码,仅适用于一个类别:
# products_controller.rb
def index
if params[:category]
@category = Category.find(params[:category])
#@products = @category.product_list
@products = @category.products
else
@category = false
@products = Product.scoped
end
@products = @products.where("title like ?", "%" + params[:title] + "%") if params[:title]
@products = @products.order("created_at).page(params[:page]).per( params[:per_page] ? params[:per_page] : 25)
@categories = Category.all
end
我注释掉的那行是我在类别模型中自己编写的帮助方法,它返回该类别及其子类别的所有产品的数组。
它的定义如下:
# app/models/category.rb
def product_list
self_and_ancestors.to_a.collect! { |x| x.products }
end
现在,当我取消注释这行代码并尝试选择一个类别时,我的产品控制器代码就会出错,例如:
undefined method `order' for #<Array:0x1887c2c>
或者
undefined method `page' for #<Array:0x1887c2c>
因为我正在使用排序和分页,所以它无法再对数组进行排序。有什么办法可以在我的控制器中获取ActiveRecord Relation元素中的所有产品吗?谢谢。
更新:当我使用以下内容时:
class Category < ActiveRecord::Base
acts_as_nested_set
attr_accessible :name, :description, :lft, :rgt, :parent_id
has_many :categorizations
has_many :products, :through => :categorizations
attr_accessor :product_list
def branch_ids
self_and_descendants.map(&:id).uniq
end
def all_products
Product.find(:all, :conditions => { :category_id => branch_ids } )
end
end
当我向控制器请求
@category.all_products
时,出现以下错误:Mysql::Error: Unknown column 'products.category_id' in 'where clause': SELECT `products`.* FROM `products` WHERE `products`.`category_id` IN (6, 8, 9)
如何获取所有包含此星座的产品?
更新2:
好的,我要开始设置悬赏了。
如果我尝试:
def all_products Categorization.find(:all, :conditions => { :category_id => branch_ids } ) end
我会再次得到“undefined method 'order' for #”错误。
我需要知道如何将一个多对多关系中的所有产品作为ActiveRecord关系获取。
更新3:
我在gist中放置了相关代码https://gist.github.com/1211231。