gpt4 book ai didi

ruby-on-rails - has_many :through, 嵌套多态关系

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:20 25 4
gpt4 key购买 nike

有没有办法直接引用(直接使用 rails,无需借助大量自定义 SQL)嵌套在多态关系后面的关系?在下面的示例中,有没有办法在引用 LayerTwo 的用户中定义 has_many 关系?

我想做(在用户中)

has_many :layer_twos, :through => layer_ones

但是这种方法没有考虑到之前通过多态关系指定的 has_many 关系。有什么建议么?它可能无法通过现有的 Rails 约定,但我想我会把这个问题推迟给比我更聪明的人。

class CreateOwners < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.timestamps
end
create_table :owners do |t|
t.timestamps
t.references :owned, :polymorphic => :true
t.references :user
end
create_table :layer_ones do |t|
end
create_table :layer_twos do |t|
t.references :layer_one
end
end
end


class Owner < ActiveRecord::Base
belongs_to :user
belongs_to :owned, :polymorphic => true
end

class User < ActiveRecord::Base
has_many :owners
has_many :layer_ones, :through => :owners, :source => :owned, :source_type => 'LayerOne'
end

class LayerOne < ActiveRecord::Base
has_many :owners, :as => :owned
has_many :layer_twos
end

class LayerTwo < ActiveRecord::Base
belongs_to :LayerOne
end

最佳答案

现在应该注意,Rails 3.1 已经嵌套了 has_many :through 内置关联。an ASCIIcast on this

关于ruby-on-rails - has_many :through, 嵌套多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1391585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com