开发者

Ruby on Rails 3 Limited Multi-table query and Array Typecasting

开发者 https://www.devze.com 2023-02-06 13:45 出处:网络
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.

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!


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
0

精彩评论

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

关注公众号