我想使用通过关联访问的params缩小集合范围
class PostsController < ApplicationController
load_and_authorize_resource
def index
if params[:event_id] then
@event = Event.find(params[:event_id])
if params[:category_id] then
@category = Category.find(params[:category_id])
@posts = Post.where(:event_id => @event.id,
:product => {:category_id => @category.id })
end
end
end
给我错误
No attribute named 'category_id' exists for table 'product'
但是'category_id'列确实存在于表'product'中。搜索此错误并没有向我显示任何有用的信息。我也尝试使用'delegate'来使属性可访问,但这也没有用。我很难过。
这是架构
create_table "posts", :force => true do |t|
t.float "quantity"
t.datetime "deadline"
t.integer "product_id"
t.integer "event_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "products", :force => true do |t|
t.string "title"
t.text "desc"
t.text "ingredients"
t.float "deposit"
t.float "cost"
t.string "units"
t.float "quantity"
t.float "deadline_hours"
t.boolean "presell_option"
t.integer "user_id"
t.integer "category_id"
t.integer "club_id"
t.datetime "created_at"
t.datetime "updated_at"
end
编辑:
当我将':product'改为':products'时,我会收到此相关错误
SQLite3::SQLException: no such column: products.category_id: SELECT "posts".* FROM "posts" WHERE (("products"."category_id" = 2 AND "posts"."event_id" = 10))
这让我更加困惑,架构说我在产品表中有category_id
答案 0 :(得分:3)
您必须使用属性名称products
而不是product
。这是规则中的一个Rails例外。
@posts = Post.joins(:product).where(:event_id => @event.id,
:products => {:category_id => @category.id })
答案 1 :(得分:2)
尝试
@posts = Post.where(:event_id => @event.id,
:products => {:category_id => @category.id })
答案 2 :(得分:1)