你希望利用多形态协会。 例如:
class Icon < ActiveRecord::Base
belongs_to :iconable, :polymorphic => true
end
class Greeting < ActiveRecord::Base
has_many :icons, :as => :iconable
end
class User < ActiveRecord::Base
has_many :icons, :as => :iconable
end
之后,您可以从问候或用户那里获得启示:
@user.icons
@greeting.icons
@icon.iconable #returns the parent type.
或者,如果您想询问某类特定类型:
Icon.where(:iconable_type => "greeting")
这种做法与你已经采取的做法不同。 采用这种方法的好处是,你能够拿到母子,而不会担心什么类型,正如你试图在座右边做其他回答一样。
你们只是需要管理一些移民,以便让一切顺利发挥作用。 可在查阅更多信息。
Edit per comment:
Strictly speaking, you re correct. You cannot have a polymorphic record which points to a User and a Greeting. However, you can make a small change and create another model, which would kind of act like a join table.
class IconConnection < ActiveRecord::Base
belongs_to :inconable, :polymorphic => true
belongs_to :icon
end
class Icon < ActiveRecord::Base
has_many :icon_connections
end
class Greeting < ActiveRecord::Base
has_many :icon_connections, :as => :iconable
has_many :icons, :through => :icon_connections
end
class User < ActiveRecord::Base
has_many :icon_connections, :as => :iconable
has_many :icons, :through => :icon_connections
end
Each IconConnection would point to either a Greeting or a User, and each of the IconConnections would point to the same Icon.
这一设置假设,您可为每个用户和问候人提供多条标语,但如果没有,你可以将<代码>has_manys改为has_one
。 页: 1