Question

I'm trying to show only 5 reviews from a specific category as opposed to 5 reviews of any category. I have posted the later which was working for comparison purposes.

The reviews have a category id index, which I then use to look up the Category name and compare that name to the Category Name of the reviews I want. I then store the 5 reviews I extract in an array (is this the most efficient way?). The reviews and categories are two separate tables.

Currently I'm getting the error "can't convert Review into Array". I'm guessing this is a typecasting issue? I don't want the Review to become an array. I want the result to be equivalent to the old code where @review holds 5 reviews. I'm not sure if I'm approaching this problem correctly.

Current Code

   def home
    @review = []
    idx = 1
    Review.find_each do |review|
      break if idx == 5
      @category = Category.find(review.category_id).category_name
      if @category == "Something"
        @review += review and idx+=1
      end
    end
  end

Old Code

def home
  @review = Review.find(:all, :limit => 5)
end

Thanks for your help!

Was it helpful?

Solution

What is happening is that review contains a Review object and you are trying to concatenate it to an array, but array concatenation only works between arrays.

i.e. [1,2,3]+[4] gives [1,2,3,4], but [1,2,3]+4 gives an error.

You can use << or push instead, or you can wrap the review object in an array:

@reviews << review

or

@reviews.push review

or

@reviews += [review]

...respectively.


Alternatively, I'm sure there's a more idiomatic way to do what you are trying to do.

I'm not sure of all the rails3 stuff yet, but something like:

Category.where(:category_name => "Something").first.reviews.limit(5)

This assumes an association between Review and Category:

In the Review model:

class Review < ActiveRecord::Base
  ...
  belongs_to :category
  ...
end

In the Category model:

class Category < ActiveRecord::Base
  ...
  has_many :reviews
  ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top