Strange ActiveRecord::AssociationTypeMismatch

后端 未结 5 472
Happy的楠姐
Happy的楠姐 2021-02-01 16:10

I am getting a very strange error when running a spec:

Failure/Error: entity = Factory.create(:entity, :name => \"Test Entity\", :creator => user)
 ActiveR         


        
相关标签:
5条回答
  • 2021-02-01 16:25

    The issue for me was in my factory definition where I was using additional factories to populate id fields. I accidentally referred to an attribute that didn't exist on the table (account, instead of account_id). See example below.

    factory Omni::CustomerAccount do
      sequence(:display_name) {|n| "test #{n}"}
      customer_id :customer  # this is correct
      account :account  # wrong - this should say account_id :account
    end
    

    Hope this helps someone.

    0 讨论(0)
  • 2021-02-01 16:30

    For the combination of Rails + Spring + factory_girl this is fixed since version v4.4.1 of factory_girl_rails (Feb 2014) see https://github.com/thoughtbot/factory_girl_rails/pull/121

    0 讨论(0)
  • 2021-02-01 16:35

    This is an error that occurs when two different versions of the model have been loaded. I used to hit it in an older version of Rails 3, since the development environment's model reloader was slightly glitched. The numbers after the class name refer to different versions of the class.

    It stands to reason that this sort of error might come up in development mode, but it shouldn't in test mode, because, by default, classes are cached. See the config/environments/test.rb file to ensure that cache_classes is set to true.

    Also check that you're on the latest version of Rails, 3.0.7. This may be a bug that has since been fixed. While we're at it, check that you're on factory_girl 1.3.3. When using the API totally correctly, which I think you're doing, the only possibilities left are that something is misconfigured or that it's a bug in someone else's code.

    0 讨论(0)
  • 2021-02-01 16:39

    Similar error might occur if you are using Spring or any other Rails application preloader, make sure you restart it.

    spring stop
    spring start
    # or usually bin/rails s or bin/rails c for console
    
    0 讨论(0)
  • 2021-02-01 16:42

    Rather than disable class caching, which can be aggravating while in development, the problem might disappear if you get your object fresh before using it. In my case I was loading an object from an association:

    desired_object = foo.bar
    

    Finding the item instead removed the problem and didn't require caching classes.

    desired_object = Bar.find(foo.bar_id)
    

    I know it isn't ideal, but perhaps this will help someone find out just why it is happening at all.

    0 讨论(0)
提交回复
热议问题