2013-09-22 24 views
0

你好,我有这个型号轨分页并在与阵列子句

模型/存储/ 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 

models/store/store_product.rb

0123通过邮寄
class Store::StoreProduct < ActiveRecord::Base 
    set_table_name "stores_products" 
    attr_accessible :store_id, :product_id 
    belongs_to :store 
    belongs_to :product 
end 

,并即时得到PARAMS [ '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模式的一部分: stores_products

id 
product_id 
store_id 

产品

id 
name 
... 

id 
name 
... 

SOLUTION(感谢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) 
+0

是否使用雷查询? –

+0

嗨,即时通讯使用will_pagination – Muflix

+0

但我可以切换到kaminari如果它有帮助 – Muflix

回答

1

试试这个

@products = Product.joins(:stores).where("#{Store::Store.table_name}.id IN (?)", params[:store_ids]).paginate(page: params[:page], order: 'name asc', per_page: 10) 

也许它会复制产品使where后添加方法uniq,适用distinct

+0

嗨谢谢你操作符IN是超级有用的但我必须键入而不是table_name? – Muflix

+1

'table_name'(这是AR方法)为模型返回一个真实的表名(它可以是'stores',但我不确定)。所以你可以按照原样使用代码或将'#{Store :: Store.table_name}'改成'your_real_table_name' – gotva

+0

啊好吧我试过了,但是 '>> Product.joins(:stores).where(“product.stores .id IN(?)“,params [:store_ids]) !! #' – Muflix