-1

下面是我的控制器代码

class ProductComparisonController < ApplicationController

def product_vote
    if !session[:category_tracker]
        @categories = Category.where(:page_id => params[:page_id]).select(:id)
        session[:category_tracker]=@categories
        session[:step]=0
        session[:number_of_categories]=@categories.count
    end

    chosen_products = session[:category_tracker][session[:step]].chosen_product_ids
    @products = Product.where(:id => chosen_products).all
    session[:step] = session[:step] + 1

end

结尾

当我运行它时,它对于类别的第一个实例运行完美。但是当步长值得到更新并且它必须从会话变量中获取第二个值时,它会给出一个错误。

错误是:(第 11 行)

未定义的方法 `chosen_product_ids' for :@new_record:Symbol

4

2 回答 2

0

您在会话中存储 ActiveRecord::Relation 而不是实际的数组。

尝试将 .all 添加到类别提取的末尾

于 2013-02-26T16:36:27.753 回答
0

您需要将 Relation 转换为要存储在会话中的数字数组。然后根据当前步骤的ID从数据库中获取对象。

class ProductComparisonController < ApplicationController

  def product_vote
    if !session[:category_tracker]
      # No need to use instance variables here.
      categories = Category.where(:page_id => params[:page_id]).select(:id)
      # Iterate the categories extracting only the ids.
      # select(:id) does not do this.
      session[:category_tracker] = categories.map(&:id)
      session[:step] = 0
      session[:number_of_categories] = categories.count
    end

    # First fetch the category
    category = Category.find(session[:category_tracker][session[:step]])
    # Then call methods on it
    chosen_products = category.chosen_product_ids
    @products = Product.where(:id => chosen_products).all
    session[:step] += 1
  end
end
于 2013-02-26T17:15:23.313 回答