开发者

Using association params in collections

I want to narrow down a collection using params accessible through association

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

Gives me the error

No attribute named 'category_id' exists for table 'product'

But the column 'category_id' does exist in the table 'product'. Searching for this error hasn't shown me anything helpful yet. I've also tried using 'delegate' to make the attribute accessible but that h开发者_JAVA百科asn't worked either. I'm stumped.

Here is the schema

  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

Edit:

When I correct ':product' to ':products' I get this related error

SQLite3::SQLException: no such column: products.category_id: SELECT "posts".* FROM "posts" WHERE (("products"."category_id" = 2 AND "posts"."event_id" = 10))

This puzzles me further, the schema says I do have the category_id in the products table


You have to use the attribute name products instead of product. This is one one Rails exceptions to the rule.

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


Try

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


You can reduce your code and make your life easier by using MetaSearch gem. It's very nice tool! Video tutorial: here. Documentation: here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜