标签: polymorphic-associations

Active Admin 有一种多态形式

我正在尝试设置一个选择菜单以将 ImageGallery 与产品相关联。ImageGallery 是多态的,因为它在几个模型之间共享。Formtastic 似乎对要做什么感到非常困惑。它试图调用一个名为 Galleryable 的方法,这是我的多态关联的名称,产品模型上的 _id (galleryable_id)。

产品

class Product < ActiveRecord::Base
  has_one :image_gallery, as: :galleryable, dependent: :destroy
  accepts_nested_attributes_for :image_gallery, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)

画廊

class ImageGallery < ActiveRecord::Base
  belongs_to :galleryable, polymorphic: true

  validates :title, presence: true

  has_many :images, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :images, :allow_destroy => true, reject_if: lambda { |t| t['file'].nil? }

end
Run Code Online (Sandbox Code Playgroud)

主动管理表单

form do |f|
    f.inputs "Details" do
      f.input :name
      f.input :category
      f.input :price
      f.input :purchase_path
      f.input :video_panels
      f.input :image_panels
      f.input :image_gallery, :as => …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails polymorphic-associations formtastic activeadmin

6
推荐指数
1
解决办法
2055
查看次数

多态关系与每种类型的单独表

我的工作其中有一些类型的数据库(如在UserAppointmentTask它可以有零个或多个等)Notes与每个类型相关联。

我遇到的实现这些关系的可能解决方案是:

  1. 多态关系
  2. 每种类型的单独表

多态关系

许多人认为这是遵循 Active Record 模式的框架最容易实现的解决方案,并且似乎是最常见的实现,我会添加一个表,其数据为morphable

显着

Mynotable_type将允许我区分相关的类型 ( User, Appointment, Task) Note,而 thenotable_id将允许我获取type相关type表中的单个记录。

优点:

  • 易于扩展,可以轻松将更多模型与多态类关联
  • 限制表膨胀
  • 生成一个可供许多其他类使用的类 (DRY)

缺点

  • 随着数据的增长,更多类型会使查询变得更加困难和昂贵
  • 不能有外键
  • 缺乏数据一致性

每种类型的单独表

或者,我可以为每种类型创建一个表,该表仅负责Notes与该类型相关联。该type_id外键可以让我快速获取个人type记录。

用户备注

被许多在线人视为代码异味,许多文章主张避免多态关系而支持替代方案(例如此处此处)。

优点:

  • 允许我们有效地使用外键
  • 高效的数据查询
  • 保持数据一致性

缺点:

  • 增加表膨胀,因为每种类型都需要一个单独的表
  • 结果在多个类中,每个类代表单独的type_notes

想法

多态关系当然是两个实现选项中更简单的一个,但是缺少外键约束并因此潜在的一致性问题感觉是错误的。

每一个表notes的关系(user_notestask_notes外键等)似乎是正确的方式(与设计模式保留),但可能会导致大量的表(除了其他types可有 …

mysql database-design polymorphic-associations database-schema laravel

6
推荐指数
1
解决办法
3093
查看次数

Laravel 多态多对多关系数据透视表与另一个模型的关系

我有如下表结构,如图所示: 数据库图

简而言之,它由几个多对多的多态关系组成,如下所示:

  • 许多resources可以有许多sources,并且数据透视表sourceables包含使数据透视表中的每一行唯一的信息catalog_numberlot_number许多资源也可能来自相同来源或不同来源,通过数据透视表上的目录号和批号来区分。

  • 许多resources也可以有许多publications附加到它,通过publicationables表与notes枢轴表

  • 许多出版物也可以描述资源的来源。

我的问题:

  1. 由于资源的来源是通过数据透视表区分的,sourceables我应该如何保存数据透视表行之间的sourceables关系publications
  2. 您可以在两者和“publicationables”之间有一个自定义中间表模型sourceables来链接到吗publications
  3. 如何检索资源及其所有出版物以及所有相应出版物的来源?

many-to-many polymorphic-associations laravel eloquent

6
推荐指数
1
解决办法
5551
查看次数

除了一个之外的所有外键都是NULL

在一个表中使用一组外键的技术的名称是什么,其中除了一个外,其他所有外键都是NULL?

换句话说,每行需要一个外键到n个不同的可能表中的一个(并且只有一个),因此您实际上拥有所有必需的外键,但除了一个之外的所有外键都是NULL.

(Django的用户可能会认为这是使用通用外键的替代方法)

database orm database-design polymorphic-associations

5
推荐指数
1
解决办法
404
查看次数

Rails类名称/类型不适用于多态has_many:through

我有一个管理借方和贷方的发票系统.基本上,发票金额是通过其借方总和获得的,余额是通过获取其贷方总额并将其减去总金额得出的.

我正在用四种型号做这件事.

  1. 发票
  2. 订单项
  3. 借方
  4. 信用

它的工作方式是通过一个连接模型(行项),它具有一个名为recordable的多态关联.乍一看似乎一切正常.但是,检查订单项会显示,当recordable_id显示正常时,recordable_type为nil.

这是代码的细分:

class Invoice < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy
  has_many :debits, :through => :line_items, :as => :recordable
  has_many :credits, :through => :line_items, :as => :recordable
end

class LineItem < ActiveRecord::Base
  belongs_to :invoice
  belongs_to :recordable, :polymorphic => true
  belongs_to :credit, :class_name => "Credit", :foreign_key => "recordable_id"
  belongs_to :debit,  :class_name => "Debit",   :foreign_key => "recordable_id"
end

class Credit < ActiveRecord::Base
  has_many :line_items, :as => :recordable, :dependent => :destroy
end

class Debit < ActiveRecord::Base …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails has-many-through polymorphic-associations

5
推荐指数
1
解决办法
3703
查看次数

如何在一个查询中跨多态表连接?

我有2个多态关联,我需要通过它来查询.

我有一个news_article表,它与团队,玩家等有多态关系.这些团队,玩家等通过感光学与照片有多态关联.

我需要找到至少有一张500px宽的图片的所有文章.

文章模型我有一个has_many:团队(通过多态表)和团队中我有一个has_many:照片(虽然是另一个多态表)

我以为我可以使用这样的连接

Article.find(:last,:joins => {:teams =>:photos},:conditions =>"photos.aspect_ratio <1.55 AND photos.aspect_ratio> 1.30")

但它不起作用.有任何想法吗?

sql activerecord ruby-on-rails polymorphic-associations

5
推荐指数
1
解决办法
1798
查看次数

如何解决三向多态关联?

首先让我说我使用的是MySQL(不是事务性的),并且无法更改.此外,为简洁明了,我在这里简化了表格.

在这个例子中,'Lesson'由它的内部属性和一个外部属性组成,它有自己的属性'Readings'.'Readings'拥有自己的密钥依赖属性和三个不同的外部属性(阅读源).

我想避免在这里产生的多态关联,但我无法绕过它.在此示例中,'Reading'表中的'sourceId'将包含三个表"ExternalURL","InternalURL"和"Book"之一的id.此外,字段"polytable"将包含上述"id"来自的表名.

有人可以花一点时间来解释如何解决这种维护RI的问题,还是为了效率而应该留下它?

感谢您的时间和考虑,

蒂姆

                       -------------
                      | ExternalURL |
                       -------------
                      | id          |
                      | badlink     |
                      | url         |
                      |             |
                      |             |
                       -------------
                            |
                            |
                            |
                           / \
 ------------          -------------          -------------
| Lesson     |-------<| Reading     |>-------| InternalURL |
 ------------          -------------          -------------
| id         |        | id          |        | id          |
| label      |        | lessonId    |        | url         |
| summary    |        | sourceId    |        |             |
| lessonOrder|        | polytable   |        |             |
| active     |        | …
Run Code Online (Sandbox Code Playgroud)

mysql normalization polymorphic-associations

5
推荐指数
1
解决办法
1988
查看次数

测试与RSpec的多态关联

我正在为多态关联编写RSpec代码.我有两个测试想法

  1. 使用Factory Girl构建多态关联
  2. 使用rails方法构建多态关联.

以下是我编写的代码片段(相关代码位于底部):

1)link_spec.rb,创建与FactoryGirl的关联.

describe "Book links" do
  let(:book) { FactoryGirl.create(:book) }
  let(:book_link) { FactoryGirl.create(:book_link, linkable: book) }

  subject{ book_link }

  it { should be_valid }

  it { should respond_to(:url) }
  it { should respond_to(:linkable) }
  its(:linkable) { should eq book }
end
Run Code Online (Sandbox Code Playgroud)

2)link_spec.rb,通过rails方法创建关联.

describe "Book links" do
  let(:book) { FactoryGirl.create(:book) }
  let(:link) { book.links.create(url: "http://example.com") }

  subject { link }

  it { should be_valid }

  it { should respond_to(:url) }
  it { should respond_to(:linkable) }
  its(:linkable) { …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails polymorphic-associations

5
推荐指数
1
解决办法
5178
查看次数

Laravel为morphMany集合指定条件

我有以下雄辩的关系

class Broker extends Eloquent{

    public function configurable(){
        return $this->morphTo();
    }
}

class ProductConfiguration extends Eloquent{

    public function productConfigurations()
    {
        return $this->morphMany('Excel\Products\ProductConfiguration','configurable');
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,我可以很容易地找到属于Broker的所有ProductConfiguration:

    $broker = Broker::find($id);
    $productConfigurations = $broker->productConfigurations;
Run Code Online (Sandbox Code Playgroud)

我不清楚的是如何指定ProductConfigurations的条件,所以如果我的ProductConfiguration有一个type字段,例如:

    $broker = Broker::find($id);
    $productConfigurations = $broker->productConfigurations->where('type' = 'reg');
Run Code Online (Sandbox Code Playgroud)

检查文档我无法确切地找到如何做到这一点.

polymorphic-associations relationships laravel

5
推荐指数
1
解决办法
917
查看次数

Ecto - 更新嵌套(多态)关联

如何使用嵌套关联更新模型(使用[Elixir,Phoenix,Ecto])?

我尝试了以下内容,将其视为其父更新的一部分,但没有成功(使用platformatec博客作为灵感).

楷模:

  schema "user" do
    has_one :address, {"users_addresses", MyApp.Address}, foreign_key: :assoc_id
  end
  @required_fields ~w(address)

------

  # Materialized in users_addresses table 
  schema "abstract table: addresses" do
    field :assoc_id,        :integer
    field :street_address,  :string
  end
Run Code Online (Sandbox Code Playgroud)

请求(PATCH):

{
  "user" => {
    "address" => {
      "street_address" => "1234"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

def update(conn, %{"id" => id, "user" => params}) do
  user = MyApp.Repo.get(User, id)
    |> MyApp.Repo.preload [:address]

  if is_nil(user) do
    send_resp(conn, 404, "")
  else
    changeset = User.changeset(user, params)

    if changeset.valid? do …
Run Code Online (Sandbox Code Playgroud)

nested elixir polymorphic-associations ecto phoenix-framework

5
推荐指数
1
解决办法
964
查看次数