[英]Issue with Rails Polymorphic Association
I'm trying to create an app for users to create a list of watches they own or wish to buy. 我正在尝试为用户创建一个应用,以创建他们拥有或希望购买的手表的列表。 I want users to be able to describe a lot of detail/attributes about their watches.
我希望用户能够描述有关其手表的许多细节/属性。 I'm trying to create a parent/child association, but not using STI, as the children models have different data and I don't want a bunch of null values in my table.
我正在尝试创建父/子关联,但不使用STI,因为子模型具有不同的数据,并且我不希望表中出现一堆空值。
I have 4 tables: 我有4张桌子:
Models 楷模
class User < ApplicationRecord
include Clearance::User
has_many :watches
end
class Watch < ApplicationRecord
belongs_to :user
belongs_to :content, polymorphic: true
end
class MechanicalWatch < Watch
has_one :watch, as: :content
end
class QuartzWatch < Watch
has_one :watch, as: :content
end
I'm not a 100% sure if I've setup the associations correctly. 我不确定是否已正确设置关联100%。 But the problem I'm having is that when I enter MechanicalWatch into the console it returns only the attributes on Watch not any of the attributes in the mechanical_watches table.
但是我遇到的问题是,当我在控制台中输入MechanicalWatch时,它仅返回Watch上的属性,而不返回Mechanical_watches表中的任何属性。 I've tried everything I can think of.
我已经尝试了所有我能想到的。 Any thoughts as to what I'm doing wrong.
关于我在做什么错的任何想法。
I'm using Rails 5, Ruby 2.3.1, and Postgres for the db. 我正在使用Rails 5,Ruby 2.3.1和Postgres作为数据库。
I don't think you want inheritance on MechanicalWatch
or QuartzWatch
. 我认为您不希望在
MechanicalWatch
或QuartzWatch
上继承。 They appear to be separate tables from Watch
. 它们似乎是与
Watch
不同的表。 The relationship you show is MechanicalWatch
"has a" Watch
, instead of MechanicalWatch
"is a" Watch
. 您显示的关系是
MechanicalWatch
“具有” Watch
,而不是MechanicalWatch
“具有” Watch
。
You would change 你会改变
class MechanicalWatch < Watch
to 至
class MechanicalWatch
From what I understand you want to be able to create a mechanical_watch instance, but still have the ability to set the fields on the watch model. 据我了解,您希望能够创建一个Mechanical_watch实例,但仍然能够在watch模型上设置字段。
Ie MechanicalWatch.new.field_on_watch = 4 即MechanicalWatch.new.field_on_watch = 4
If that's correct then u can look at this: 如果正确,那么您可以看一下:
http://api.rubyonrails.org/classes/Module.html http://api.rubyonrails.org/classes/Module.html
The pattern your looking for is delegation. 您寻找的模式是委托。
An important question to ask though: do you plan to use watches in a polymorphic way. 不过,有一个重要问题要问:您打算以多态方式使用手表吗? Ie Will u show all types of watches on the same page?
即可以在同一页面上显示所有类型的手表吗? Or will different watches be displayed separately?
还是会分开显示不同的手表?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.