简体   繁体   中英

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.

A user "has_many" emails. Emails "belong_to" user. Here's my code:

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

Then, in the console:

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

Indeed, this "NoMethodError" persists no matter what.

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

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. 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 .

You're confusing the concept of classes and instances. You need an instance of the User class in order to build associated relations. 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.

Try something like:

my_user = User.new
my_user.emails.build

请这样使用

@email = User.first.emails.build

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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