Home Cannot create has_one association, throws undefined method new error
Reply: 0

Cannot create has_one association, throws undefined method new error

user1519
1#
user1519 Published in May 22, 2018, 12:28 am

I'm trying to build a one to one association in Rails 5, basically, I just want users to connect to only one user.

So I want to be able to do this in my rails console:

User.first.relationship.new(:partner_id => 2)

To be able to set and retrieve the partner of a particular user.

I'm using a join model, called Relationship.

class Relationship < ApplicationRecord
  belongs_to :user
  belongs_to :partner, :class_name => "User"
end

And a User model.

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable

  has_one :relationship
  has_one :partner, :through => :relationship

  validates_presence_of :first_name, :last_name
end

I generated the Relationship model like this: rails g model Relationship user:references partner_id:integer.

When I do a User.first.relationship.new() it throws a NoMethodError: undefined method new for nil:NilClass in the rails console.

However, when I change the User model from has_one to has_many:

has_many :relationships
has_many :partners, :through => :relationships

It works, but I want to have only a one to one relationship using a self-referential association.

What am I doing wrong? Thanks!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301167 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO