你好我有这个模型
模型/商店/store.rb
class Store::Store < ActiveRecord::Base
attr_accessible :name
has_many :store_products
has_many :products, :through => :store_products
end
模型/product.rb
class Product < ActiveRecord::Base
attr_accessible :name ...
has_many :store_products
has_many :stores, :through => :store_products
end
模型/商店/store_product.rb
class Store::StoreProduct < ActiveRecord::Base
set_table_name "stores_products"
attr_accessible :store_id, :product_id
belongs_to :store
belongs_to :product
end
我通过发布到控制器操作获取参数 ['store_ids']
>> params['store_ids']
=> ["1", "2"]
我在哪里有这个代码
>> @products = Product.joins(:stores).where("stores.id IN (?)", params[:store_ids])
它抛出错误
#<NameError: uninitialized constant Product::StoreProduct>
我该如何解决这个问题(仅在某些商店中选择产品)?:-) 谢谢
编辑:更多信息:
文件夹结构
app/controllers/store/main_controller.rb
app/controllers/store/stores_controller.rb
app/models/store/store.rb
app/models/store/store_product.rb
app/models/product.rb
代码在
class Store::MainController < ApplicationController
def index
if params['store_ids'] then
@products = Product.joins(:stores)...
else
@products = Product.paginate page: params[:page], order: 'name asc', per_page: 10
end
end
DB Schema 的一部分: stores_products
id
product_id
store_id
产品
id
name
...
商店
id
name
...
解决方案(感谢 Gotva)
class Product < ActiveRecord::Base
attr_accessible :name, ...
has_many :store_products, class_name: "Store::StoreProduct"
has_many :stores, :through => :store_products
end
class Store::Store < ActiveRecord::Base
attr_accessible :name
has_many :store_products, class_name: "Store::StoreProduct"
has_many :products, :through => :store_products
end
class Store::StoreProduct < ActiveRecord::Base
set_table_name "stores_products"
attr_accessible :store_id, :product_id
belongs_to :store, class_name: "Store::Store"
belongs_to :product, class_name: "Product"
end
最后
@products = Product.joins(:stores).where("stores.id IN (?)", params[:store_ids]).paginate(page: params[:page], order: 'products.name asc', per_page: 10)