簡體   English   中英

Ruby on Rails-從has_and_belongs_to訪問兒童關系

[英]Ruby on Rails - Access Children Relation from has_and_belongs_to

我對此有疑問,在Internet上的任何地方都找不到答案。

這是我得到的錯誤:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "region_translations"
LINE 1: ...ions"."id" = "orders_regions"."region_id" WHERE ((region_tra...

所以我有Order類,它具有以下關系:

has_and_belongs_to_many :regions, :trough => :regions_orders

然后,在rails admin部分中有此方法:

rails_admin do
    parent Booklet

    list do

      field :first_name
      field :last_name
      field :sent
      field :address
      field :state
      field :city
      field :postal_code

      field :booklets_orders
      field :regions
      field :language

      field :regions do
          searchable ({Region::Translation => :title})
          sortable({:region_translations => :title})
          filterable true
          queryable true
      end

然后,我看到該區域出現在可能的過濾器中,但是如果我嘗試一個請求,則會收到上面提到的錯誤。 據我了解,這是因為它沒有在表orders_regions.region_idregion_translation之間進行左region_translation 但是老實說,我不確定如何訪問它,在regionregion_translation之間建立了正確的關系(它在站點中的任何地方都有效),所以我被困在那里……有什么線索嗎?

這是您可以顯式設置的方法:

class Order < ApplicationRecord
  has_many :regions_orders
  has_many :regions, through: :regions_orders
end

class RegionsOrder < ApplicationRecord
  belongs_to :order
  belongs_to :region
end

class Region < ApplicationRecord
  has_many :regions_orders
  has_many :orders, through: :regions_orders
end

region_orders表是聯接表,將具有order_id和region_id列以及您希望放入其中的任何其他列。 這些額外的列應反映某個實體,該實體是該行的區域和順序的組合。 例如,您可能有一個名為“數量”的附加列,該列表示該區域中該訂單的已售出單位數量。 因此,聯接表的一行分別對應於order_id,region_id和數量,如下所示:22、12、1000。這意味着訂單的區域12中售出了1000個單位(這是regions表中該區域的id) 22(這是訂單表中訂單的ID)。 我不知道您要建模的內容,但是希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM