Ruby on rails 在集合中使用关联参数

Ruby on rails 在集合中使用关联参数,ruby-on-rails,collections,delegates,Ruby On Rails,Collections,Delegates,我想使用可通过关联访问的参数缩小集合范围 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.f

我想使用可通过关联访问的参数缩小集合范围

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
但表“product”中确实存在“category_id”列。搜索此错误尚未向我显示任何有用信息。我还尝试使用“委托”使属性可访问,但这也不起作用。我被难住了

这是模式

  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“to”:product“时,我会收到此相关错误

SQLite3::SQLException: no such column: products.category_id: SELECT "posts".* FROM "posts" WHERE (("products"."category_id" = 2 AND "posts"."event_id" = 10))
这让我更加困惑,模式说我在products表中确实有category_id

    @posts = Post.where(:event_id => @event.id, 
              :products => {:category_id => @category.id })
试一试


您必须使用属性名
products
,而不是
product
。这是该规则的一个例外

@posts = Post.joins(:product).where(:event_id => @event.id, 
                  :products => {:category_id => @category.id })

您必须使用属性名
products
,而不是
product
。这是该规则的一个例外

@posts = Post.joins(:product).where(:event_id => @event.id, 
                  :products => {:category_id => @category.id })

通过使用元搜索gem,您可以减少代码并使您的生活更轻松。这是一个非常好的工具!视频教程:。文档:。

通过使用MetaSearch gem,您可以减少代码并使您的生活更轻松。这是一个非常好的工具!视频教程:。文档:。

我尝试更改此项,请参阅我的编辑,对错误有何看法?还有什么我需要包括的吗?更新了我的答案看一看。是的,很有效,谢谢。我想我必须了解joins的作用以及我需要在哪里使用它。我尝试过更改它,查看我的编辑,对错误有什么想法吗?还有什么我需要包括的吗?更新了我的答案看一看。是的,很有效,谢谢。我想我必须了解Join的功能以及我需要在哪里使用它。谢谢,我将为搜索功能实现此功能。我之所以在这里使用params,是因为可以使用url查看某些类别的帖子。元搜索是嵌套路由的好替代品吗?我不确定。但我认为,在您的情况下,元搜索并不是最好的解决方案。谢谢,我将为搜索功能实现此功能。我之所以在这里使用params,是因为可以使用url查看某些类别的帖子。元搜索是嵌套路由的好替代品吗?我不确定。但我认为,在你的情况下,元搜索并不是最好的解决方案。@thejonster,你确定数据库已经完全迁移了吗?只是确认一下。是的,这些表是在我的项目早期迁移的(我也只是仔细检查了一下),我会尝试迁移每一个更改。@thejonster,你确定数据库已经完全迁移了吗?只是确认一下。是的,这些表是在我的项目早期迁移的(我也只是仔细检查了一下),我会尝试迁移每一个更改。