Rails 关联不起作用
Rails Associations don't work
我阅读了很多教程,并准确地复制了他们的代码,但他们声称对他们有用的东西对我却不起作用。
我正在建立最基本的 "has_many" 和 "belongs_to" 关联,但 rails 拒绝承认任何关联。
一个用户 "has_many" 封邮件。电子邮件 "belong_to" 用户。这是我的代码:
user.rb
class User < ActiveRecord::Base
unloadable
has_many :emails
accepts_nested_attributes_for :emails,
:allow_destroy => true,
# :reject_if => :all_blank
end
email.rb
class Email < ActiveRecord::Base
unloadable
belongs_to :user
end
然后,在控制台中:
User.emails.build
NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>
的确,这个 "NoMethodError" 无论如何都会存在。
截至目前,我的猜测是我在安装 rails 时硬件中的一个电容器烧坏了,导致除了这件事之外一切正常。或者可能是其他原因 :p
编辑:
另一次控制台尝试:
my_user = User.new
my_user.emails.build
也会导致未定义的 "emails" 方法。
我注意到我的原始用户 class 末尾有一个错误的逗号;删除它,我得到这个错误:
ActiveRecord::UnknownAttributeError: unknown attribute 'user_id' for Email.
您混淆了 classes 和实例的概念。您需要 User
class 的实例才能建立关联关系。您收到的错误 (NoMethodError: undefined method emails for #<Class:0x00000006c16e88>
) 暗示了这一点,因为它告诉您您正在尝试在 Class 对象上调用方法 emails
。
试试这样的东西:
my_user = User.new
my_user.emails.build
请这样使用
@email = User.first.emails.build
首先,您需要确保数据库中的电子邮件 table 具有 user_id
属性。如果您没有,可以通过迁移添加它。
然后,您需要告诉 Rails 您想要查看用户电子邮件的哪个实例。因此,您需要确保数据库中有一个用户 (user = User.create
),然后可以使用 user.emails
找到该用户的电子邮件。
我阅读了很多教程,并准确地复制了他们的代码,但他们声称对他们有用的东西对我却不起作用。
我正在建立最基本的 "has_many" 和 "belongs_to" 关联,但 rails 拒绝承认任何关联。
一个用户 "has_many" 封邮件。电子邮件 "belong_to" 用户。这是我的代码:
user.rb
class User < ActiveRecord::Base
unloadable
has_many :emails
accepts_nested_attributes_for :emails,
:allow_destroy => true,
# :reject_if => :all_blank
end
email.rb
class Email < ActiveRecord::Base
unloadable
belongs_to :user
end
然后,在控制台中:
User.emails.build
NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>
的确,这个 "NoMethodError" 无论如何都会存在。
截至目前,我的猜测是我在安装 rails 时硬件中的一个电容器烧坏了,导致除了这件事之外一切正常。或者可能是其他原因 :p
编辑:
另一次控制台尝试:
my_user = User.new
my_user.emails.build
也会导致未定义的 "emails" 方法。
我注意到我的原始用户 class 末尾有一个错误的逗号;删除它,我得到这个错误:
ActiveRecord::UnknownAttributeError: unknown attribute 'user_id' for Email.
您混淆了 classes 和实例的概念。您需要 User
class 的实例才能建立关联关系。您收到的错误 (NoMethodError: undefined method emails for #<Class:0x00000006c16e88>
) 暗示了这一点,因为它告诉您您正在尝试在 Class 对象上调用方法 emails
。
试试这样的东西:
my_user = User.new
my_user.emails.build
请这样使用
@email = User.first.emails.build
首先,您需要确保数据库中的电子邮件 table 具有 user_id
属性。如果您没有,可以通过迁移添加它。
然后,您需要告诉 Rails 您想要查看用户电子邮件的哪个实例。因此,您需要确保数据库中有一个用户 (user = User.create
),然后可以使用 user.emails
找到该用户的电子邮件。