Rails 5:循环两个具有关联的表

时间:2019-04-11 13:58:50

标签: ruby-on-rails

我有以下表格和关联:

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

该错误不再出现,但是折扣也没有出现。任何想法为什么会这样?

1 个答案:

答案 0 :(得分:0)

您提到了

class Product < ApplicationRecord
  has_one :discount
end

这意味着每种产品只有一次折扣。

然后可以通过以下方式获得折扣

 <%= product.discount %>

如果一种产品有很多折扣,则将型号更改为:

class Product < ApplicationRecord
  has_many :discounts
end

如果关联被更改,则在每个循环下面将起作用:

 <% product.discount.each do |discount| %>
     <%= discount %>
<% end %>