Jake
Jake

Reputation: 1186

Displaying a product based on category value in table | Ruby On Rails

I replaced the name "Product" with "Pack" in my application. I was wondering if it was possible to display certain products based on their category_id string value in the "packs" table, without a category table. (only using the packs table to organize each pack on the packs' index. A pack can only belong to one category.

I am currently trying to do this via this code in my PacksController:

def index
  @title = 'Products';
  @packs = Pack.includes(:category_id).group_by { |pack| pack.category_id }
end

And trying to display the pack if it has the same :category_id as the do .erb:

<% @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 %>

When I run this code I get an error: Association named 'category_id' was not found on Pack; perhaps you misspelled it? but I don't know if this is even a possible approach to doing this.

This is my db table for "packs":

  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

This is what I've seeded into the db "confidential are changed:

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>",

)

Upvotes: 1

Views: 174

Answers (1)

The Lazy Log
The Lazy Log

Reputation: 3574

Simply remove includes(:category_id) in your query and it should work fine. You are trying to eager load an association named category_id but it does not exist (and it is not a convention in Rails to have a association like that, it should be a foreign key).

@packs = Pack.all.group_by(&:category_id)

In views:

<% @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 %>

You might have to handle some exceptional cases such as when there are no category id called "sample-pack". I leave it to you to deal with.

Upvotes: 1

Related Questions