我在我的应用程序中将“Product”替换为“Pack”。我想知道是否有可能在“包”表中显示基于其category_id字符串值的某些产品,而没有类别表。 (仅使用包表来组织包装索引上的每个包装。包装只能属于一个类别。
我目前正在尝试通过我的PacksController中的代码执行此操作:
def index
@title = 'Products';
@packs = Pack.includes(:category_id).group_by { |pack| pack.category_id }
end
如果广告包与:category_id
.erb具有相同的do
,则尝试展示广告资源:
<% @packs.select { |pack| pack.category_id == 'sample-pack' }.each do %>
<div class="col-md-4 pack-pad">
<%= link_to pack_path(pack) do %>
<%= image_tag("#{pack.art_link}", :alt => "Sample pack cover, album art", :width => 333, :height => 333, class: "feat-img") %>
<% end %>
</div>
<% end %>
当我运行此代码时,我收到一个错误:Association named 'category_id' was not found on Pack; perhaps you misspelled it?
但我不知道这是否是一种可行的方法。
这是我的“包”的数据库表:
create_table "packs", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "pack_type"
t.string "audio_embed"
t.string "art_link"
t.string "pack_class"
t.string "sku"
t.string "download_url"
t.string "category_id"
end
这就是我在数据库中所看到的“机密被更改:
theHunt = Pack.create!(
title: "The Hunt",
description: "<description>",
price: "25",
pack_class: "Action",
pack_type: "Paid",
category_id: "sample-pack",
sku: "samplePack1",
art_link: "<path>",
download_url: "<link>",
)
答案 0 :(得分:1)
只需在查询中删除includes(:category_id)
,它就可以正常运行。您正试图加载一个名为category_id
的关联,但它不存在(并且Rails中的约定不是这样的关联,它应该是外键)。
@packs = Pack.all.group_by(&:category_id)
观点:
<% @packs['sample-pack'].each do |pack| %>
<div class="col-md-4 pack-pad">
<%= link_to pack_path(pack) do %>
<%= image_tag("#{pack.art_link}", :alt => "Sample pack cover, album art", :width => 333, :height => 333, class: "feat-img") %>
<% end %>
</div>
<% end %>
您可能必须处理一些例外情况,例如没有名为“sample-pack”的类别ID。我留给你处理。