Search code examples
ruby-on-railsfactory-bot

Rails association.create and association.create! returns nil


I'm just throwing this out there because I really can't figure this out. When I call for instance user.articles.create! { title: 'blah' } nil is returned but the object is created. I've not seen anything like this before and was wondering if someone else has?

I've tried rails 3.2.13 and 3.2.12 and they both do the same thing.

EDIT

In active record both create and create! ends up IN THIS METHOD that is supposed to return the record or throw an exception.

def create_record(attributes, options, raise = false, &block)
  unless owner.persisted?
    raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
  end

  if attributes.is_a?(Array)
    attributes.collect { |attr| create_record(attr, options, raise, &block) }
  else
    transaction do
      add_to_target(build_record(attributes, options)) do |record|
        yield(record) if block_given?
        insert_record(record, true, raise)
      end
    end
  end
end

Solution

  • If I'm not mistaken Factory Girl mimic the actual object you're dealing with through your predefined factory. Therefor User#articles might not return what you think it is when called on a factory.

    Changing

    user.articles.create! { title: 'blah' }
    

    to

    create(:article, user: user, title: 'blah')
    

    should enforce the association through Factory Girl's interface.