Ruby on rails ActiveRecord::AssociationTypeMismatch与接受的\u嵌套的\u属性\u
我有Ruby on rails ActiveRecord::AssociationTypeMismatch与接受的\u嵌套的\u属性\u,ruby-on-rails,Ruby On Rails,我有用户和电子邮件表,其中一个用户有一个电子邮件(作为系统中的登录名)。但用户可能有许多电子邮件作为自己的联系人 class User < ApplicationRecord has_secure_password has_one :email # has_many :phones, as: :contactable accepts_nested_attributes_for :email end class Email < ApplicationRecord
用户
和电子邮件
表,其中一个用户
有一个电子邮件
(作为系统中的登录名)。但用户可能有许多电子邮件作为自己的联系人
class User < ApplicationRecord
has_secure_password
has_one :email
# has_many :phones, as: :contactable
accepts_nested_attributes_for :email
end
class Email < ApplicationRecord
belongs_to :contactable, polymorphic: true
accepts_nested_attributes_for :contactable
validates :email, presence: true, uniqueness: true
end
当我尝试发送这样的请求时
{
"email": "test@test.ru",
"phone": "+799999999999",
"password": "test",
"first_name": "First-name",
"last_name": "Last-name",
"patronymic": "Patronymic"
}
我有这个错误
"exception": "#<ActiveRecord::AssociationTypeMismatch: Email(#70266002240460) expected, got \"test@test.ru\" which is an instance of String(#47039052873240)>"
我有错误
{
"email.contactable": [
"must exist"
]
}
子问题:如何去除电子邮件属性?您的用户没有一个名为email的列,它有一个关联,它是一个新的电子邮件对象,具有自己的属性
如果它只是一个列,那么您可以将参数设置为:
user: {
name: 'Fred', # this is a column on users
email: 'fred@example.com' # this is another column on users
}
但是,您需要它像一个单独的模型一样工作。现在,您的电子邮件模型本身就是一个数据库表,并且有一个列,例如“email”,对吗?如果是这样的话,那么你就需要参数来做类似这样的事情:
user: {
name: 'Fred', # this is a column on users
email: { # this tells us that it's another object called 'email'
email: 'fred@example.com' # this is a column on emails
}
}
显然,您需要重命名列以匹配自己的列
我还要指出,在您的许可证中,您既有一封电子邮件作为用户专栏,也有一封电子邮件作为email\u attributes
——这表示另一个称为email的关联模型的属性。您是说您的用户有一个名为email
的属性,并且您还建立了的关系:email
。您不能有关联,与该属性同名的属性将被覆盖。我犯了一个错误。用所属的替换了中的一个
。您的问题仍未更新。请用正确的信息更新问题,因为它仍然反映您有一个用户有多封或一封电子邮件我刚刚更新了问题我的想法是,该用户有一封电子邮件作为登录名,有许多电子邮件和电话作为您的联系人
user: {
name: 'Fred', # this is a column on users
email: 'fred@example.com' # this is another column on users
}
user: {
name: 'Fred', # this is a column on users
email: { # this tells us that it's another object called 'email'
email: 'fred@example.com' # this is a column on emails
}
}