Rails关联不起作用

时间:2016-08-31 13:26:21

标签: ruby-on-rails ruby ruby-on-rails-3

我已阅读了很多教程,并完全复制了他们的代码,但他们声称对他们有用的东西并不适用于我。

我正在制作一个最基本的“has_many”和“belongs_to”关联,但rails拒绝承认任何关联。

用户“has_many”电子邮件。电子邮件“belongs_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”仍然存在。

截至目前,我的猜测是我的硬件中的电容器在安装导轨时烧坏了,导致一切都工作,除了这一件事。或者也许是别的东西:p

编辑:

另一个控制台尝试:

my_user = User.new
my_user.emails.build

还会导致未定义的“电子邮件”方法。

我注意到我的原始用户类最后有一个坏的逗号;删除它,我收到此错误:

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

3 个答案:

答案 0 :(得分:2)

First, you'll need to make sure you have a user_id attribute on your email table in the database. 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. 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.

答案 1 :(得分:1)

你混淆了类和实例的概念。您需要User类的实例才能构建关联关系。您收到的错误(NoMethodError: undefined method emails for #<Class:0x00000006c16e88>)暗示了这一点,因为它告诉您正在尝试在Class对象上调用方法emails

尝试类似:

my_user = User.new
my_user.emails.build

答案 2 :(得分:1)

请像这样使用

@email = User.first.emails.build