0

I have a 1:many relationship between a company table and a user table (1 company has many users). It seems however that a company_id is a mandatory value for a user. At least I belief that is the cause of the error I get on seeding: ActiveRecord::AssociationTypeMismatch: Company(#29826300) expected, got String(#8555320). How can I make the relationship optional, as to also include users without a company?


In my users migration file I have:

t.references :company, index: true,    foreign_key: true
add_index :users, [:company_id, :username]  #

In my company model file:

has_many :users
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true

In my user model file:

belongs_to :organization
4
  • It sounds more like you are doing something wrong in your seeds file like User.create(company: 'nil') can you please add it to the question?
    – max
    Jun 22, 2015 at 22:13
  • My seeds file was working, I then added the relationship. Next I made no changes to my seeds file and seeded (after a new creation/migration of the table). Then I got the error message on seeding.
    – Nick
    Jun 22, 2015 at 22:15
  • Given the code I have, should that make the relationship optional normally? It does succesfully seed if I remove the user records from the seeds file.
    – Nick
    Jun 22, 2015 at 22:17
  • Rails associations are always "optional". You can add validations which enforce rules on associations. Anyway the error is not in the code you have added to your question. Follow the stack trace from the error message and add the offending code and then maybe we can help you solve the issue.
    – max
    Jun 22, 2015 at 22:20

1 Answer 1

0

I found the cause. As Maxcal said its not the code in the OP that is the problem. Before adding the association, the user model already had a variable called company. After adding the association, Rails expects that variable to be dedicated to the association. I didn't expect this and thought company_id to take on this role. Renaming the variable solved it.

2
  • Good. One potential issue that I spotted though is that if user.organisation points to a Company you need to specify it in the relation like so: belongs_to : organization, class_name: 'Company'
    – max
    Jun 22, 2015 at 22:32
  • Ah, thanks, that indeed prevents future problems when I start using the association.
    – Nick
    Jun 22, 2015 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.