bntzio
bntzio

Reputation: 1324

Cannot create has_one association, throws undefined method new error

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!

Upvotes: 1

Views: 887

Answers (1)

Riley Thompson
Riley Thompson

Reputation: 61

Try User.first.create_relationship(relationship_params) ?

Upvotes: 1

Related Questions