简体   繁体   English

Rails协会不起作用

[英]Rails Associations don't work

I've read through many tutorials, and copied their code exactly, yet what they claim works for them doesn't work for me. 我通读了许多教程,并准确地复制了他们的代码,但是他们声称对他们有用的内容对我来说不起作用。

I'm making a most basic "has_many" and "belongs_to" association, but rails refuses to acknowledge any association whatsoever. 我正在建立最基本的“ has_many”和“ belongs_to”关联,但是Rails拒绝承认任何关联。

A user "has_many" emails. 用户“ has_many”电子邮件。 Emails "belong_to" user. 向“ belong_to”用户发送电子邮件。 Here's my code: 这是我的代码:

user.rb 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 email.rb

class Email < ActiveRecord::Base
  unloadable

  belongs_to :user
end

Then, in the console: 然后,在控制台中:

User.emails.build
NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>

Indeed, this "NoMethodError" persists no matter what. 确实,无论如何,此“ NoMethodError”都会持续存在。

As of now, my guess is that a capacitor in my hardware burnt out while I was installing rails, causing everything to work except this one thing. 到目前为止,我的猜测是我在安装滑轨时硬件中的电容器烧坏了,除了这件事之外,其他所有东西都可以正常工作。 Or maybe it's something else :p 或者也许是其他的东西:p

EDIT: 编辑:

Another console attempt: 另一个控制台尝试:

my_user = User.new
my_user.emails.build

Also results in an undefined "emails" method. 也导致未定义的“电子邮件”方法。

I noticed that my original user class has a bad comma at the end; 我注意到我的原始用户类末尾有一个不好的逗号。 removing that, I get this error: 删除那,我得到这个错误:

ActiveRecord::UnknownAttributeError: unknown attribute 'user_id' for Email.

First, you'll need to make sure you have a user_id attribute on your email table in the database. 首先,您需要确保数据库中的电子邮件表上具有user_id属性。 If you don't have one, you can add it with a migration. 如果您没有,则可以通过迁移添加它。

Then, you need to tell Rails which instance of a user's emails you want to look at. 然后,您需要告诉Rails您要查看用户电子邮件的哪个实例。 So, you'll need to make sure you have a user in the database ( user = User.create ) and then that user's emails can be found using user.emails . 因此,您需要确保在数据库中有一个用户( user = User.create ),然后可以使用user.emails找到该用户的电子邮件。

You're confusing the concept of classes and instances. 您会混淆类和实例的概念。 You need an instance of the User class in order to build associated relations. 您需要User类的实例才能建立关联关系。 The error you're getting ( NoMethodError: undefined method emails for #<Class:0x00000006c16e88> ) hints to this, since it's telling you you're trying to call the method emails on a Class object. 您收到的错误( NoMethodError: undefined method emails for #<Class:0x00000006c16e88> )提示了此信息,因为它告诉您正在尝试在Class对象上调用方法emails

Try something like: 尝试类似:

my_user = User.new
my_user.emails.build

请这样使用

@email = User.first.emails.build

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM