使用group_by时,#<array>的未定义方法`image'

时间:2016-06-09 23:39:44

标签: ruby-on-rails ruby ruby-on-rails-4

你们有没有人能指出我正确的方向?我试图在views/pages/index.html.erb上显示图片,图片通过views/products/new.html.erb部分上传到_form.html.erb。然后,每个产品/图片属于我可以在_navbar.html.erb中选择的类别,然后定向到views/categories/show.html.erb以查看该类别中每个产品的图片,依此类推。

一切正常

但现在我想在views/pages/index.html.erb上显示每个类别中最后添加的图片,我总是收到此错误:undefined method 'image' for #<Array:0x007f8d1fb19ff0>

我现在很迷茫,希望有人可以引导我走上正确的道路。

我的代码ID是这样的:

pages_controller.rb

class PagesController < ApplicationController
  def index
      @products = Product.all.order(created_at: :desc).group_by(&:category_id)
  end

  def about
  end

  def location
  end

  def stockists
  end
end

视图/页/ index.html.erb

    <% @products.each do |product| %>
        <div class="col-lg-3 col-sm-6 col-xs-12 center-block " >
            <%= image_tag product.image.url(:medium) %>
            <p><%= product.name %></p>
            <p><%= product.category.name %></p>
        <% end %>
        </div>

然后我有,products.rb和category.rb

product.rb

class Product < ActiveRecord::Base
    mount_uploader :image, ImageUploader

    validates_presence_of :name, :price
    validates_numericality_of :price

    belongs_to :category
end

category.rb

class Category < ActiveRecord::Base
    has_many :products

end

这是schema.rb的一部分

  create_table "products", force: :cascade do |t|
    t.string   "name"
    t.string   "description"
    t.float    "price"
    t.string   "image"
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
    t.integer  "category_id", default: 1
  end

  add_index "products", ["category_id"], name: "index_products_on_category_id", using: :btree

最后有这部分

 add_foreign_key "order_items", "orders", on_delete: :cascade
 add_foreign_key "order_items", "products"
 add_foreign_key "orders", "users", on_delete: :cascade
 add_foreign_key "products", "categories"
end

1 个答案:

答案 0 :(得分:1)

您在控制器中使用group_by,这是一种可枚举的方法,返回由Product键入的category_id数组的哈希

@product = {
  :category1 => [#<Product category_id=1>, #<Product category_id=1>, ...],
  :category2 => [#<Product category_id=2>, #<Product category_id=2>, ...]
}

当您在视图中循环浏览@products时,循环遍历哈希,其中每次迭代传递数组

product变量不包含产品,而是包含一系列产品。

<% @products.each do |product| %>             # product is type Array!
  <%= image_tag product.image.url(:medium) %> # Array.image throws an error! 
<% end %>  

您必须创建一个外部循环来逐步执行散列。

<% @products.each do |category, products| %>
  <% products.each do |product| %>
    # do stuff       
  <% end %>
<% end %>