Patrick A.
Patrick A.

Reputation: 103

Rails 3, has_one belongs_to issues

I've got a model called User with:

has_one :etho

And a model called Etho with:

belongs_to :user

I've got a build on the create method in User:

@user.build_etho

And for some reason when I login, I am still able to create more than 1 etho! A user should only have 1 etho and shouldn't be able to create any more than 1! Why isn't this working?

Upvotes: 0

Views: 126

Answers (2)

bento
bento

Reputation: 2099

I think you misunderstand what build_etho does - according to the documentation

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

"build_association(attributes = {}) Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved."

that is, each time you call build_etho, a new Etho object is created (build, that is, not saved in the db yet) - a user will always be linked to exactly one, probably the last created, but calling build_etho will not guarantee that only one is created from your User object!

What exactly are you trying to do?

Upvotes: 2

ecoologic
ecoologic

Reputation: 10430

Your reference id column should be in your users table, can you confirm please?

Which means that in your users migration you should have

t.references :ethos

Upvotes: 0

Related Questions