У меня есть следующие таблицы и ассоциации:
class Discount < ApplicationRecord
belongs_to :product, optional: true
end
class Product < ApplicationRecord
has_one :discount
end
create_table "products", force: :cascade do |t|
t.string "title"
t.string "price"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "discounts", force: :cascade do |t|
t.string "percentage"
t.date "from"
t.date "until"
t.integer "product_id", default: [], array: true
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_discounts_on_product_id", using: :gin
end
И я пытаюсь просмотреть продукты в представлении и показать скидки на каждый продукт следующим образом:
<% @products.each do |product| %>
<%= number_to_currency product.price %>
<%= product.title.capitalize %>
<%= product.description.capitalize %>
<% product.discount.each do |discount| %>
<%= discount %>%</span>
<% end %>
Если я просто перебираю продукты, все работает нормально, но когда я добавляю код для прохождения скидок, я получаю следующую ошибку:
PG::InvalidTextRepresentation: ERROR: malformed array literal: "137"
DETAIL: Array value must start with "{" or dimension information.
: SELECT "discounts".* FROM "discounts" WHERE "discounts"."product_id" = $1 LIMIT $2
Любая идея о том, чего мне здесь не хватает, икак заставить это работать?
Обновление 1
Хорошо, я сделал это, как многие предлагали:
rails g migration CreateJoinTableDiscountsProducts discount product
class CreateJoinTableDiscountsProducts < ActiveRecord::Migration[5.2]
def change
create_join_table :discounts, :products do |t|
t.index [:discount_id, :product_id]
t.index [:product_id, :discount_id]
end
end
end
class Product < ApplicationRecord
has_and_belongs_to_many :discounts
end
class Discount < ApplicationRecord
has_and_belongs_to_many :products
end
<% @products.each do |product| %>
<%= number_to_currency product.price %>
<%= product.title.capitalize %>
<%= product.description.capitalize %>
<% product.discounts.each do |discount| %>
<%= discount.percentage %>
<% end %>
<% end %>
Ошибка больше не появляетсяно скидки тоже не появляются.Есть идеи, почему это происходит?