rails pagination和where子句与数组

时间:2013-09-22 19:40:40

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

您好我有这个型号

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

并通过post to controller action

获取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 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)

1 个答案:

答案 0 :(得分: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)

也许它会复制产品,因此在uniq之后添加方法where,这会在查询中应用distinct