Jwan622
Jwan622

Reputation: 11639

Create a model that belongs_to another in Rails 5

This is my image model:

class Image < ApplicationRecord
  belongs_to :user

  mount_uploader :avatar, AvatarUploader
end

I can't even create an image in console without a user? Did this change from Rails 4?

Image.create
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Image id: nil, user_id: nil, title: nil, created_at: nil, updated_at: nil, avatar: nil>
2.2.4 :018 > Image.create(title: "hi")
   (0.3ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Image id: nil, user_id: nil, title: "hi", created_at: nil, updated_at: nil, avatar: nil>
2.2.4 :019 > u = User.create
   (0.1ms)  begin transaction
  SQL (0.2ms)  INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", 2016-03-17 04:27:09 UTC], ["updated_at", 2016-03-17 04:27:09 UTC]]
   (8.6ms)  commit transaction
 => #<User id: 6, name: nil, created_at: "2016-03-17 04:27:09", updated_at: "2016-03-17 04:27:09">
2.2.4 :020 > u.images << Image.create
   (0.1ms)  begin transaction
   (0.0ms)  rollback transaction
   (0.0ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "images" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?)  [["user_id", 6], ["created_at", 2016-03-17 04:27:16 UTC], ["updated_at", 2016-03-17 04:27:16 UTC]]
   (7.8ms)  commit transaction
  Image Load (0.2ms)  SELECT "images".* FROM "images" WHERE "images"."user_id" = ?  [["user_id", 6]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Image id: 3, user_id: 6, title: nil, created_at: "2016-03-17 04:27:16", updated_at: "2016-03-17 04:27:16", avatar: nil>]>

I can't get my factories setup:

FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "jeff#{n}" }
    after(:build) do |user, eval|
      user.images << build(:image)
    end
  end


  factory :image do
    avatar File.open(File.join(Rails.root, '/spec/support/images/blueapron.jpg'))
  end
end

These are my error messsages:

* image - Validation failed: User must exist (ActiveRecord::RecordInvalid)
    from /Users/Jwan/.rvm/gems/ruby-2.2.4/gems/factory_girl-4.5.0/lib/factory_girl/linter.rb:4:in `lint!'
    from /Users/Jwan/.rvm/gems/ruby-2.2.4/gems/factory_girl-4.5.0/lib/factory_girl.rb:59:in `lint'
    from /Users/Jwan/Dropbox/programming/rails/carrierwave_s3/spec/support/factory_girl.rb:10:in `block (2

Upvotes: 1

Views: 287

Answers (1)

Dharam Gollapudi
Dharam Gollapudi

Reputation: 6438

Yes it changed in rails 5. If you need previous behavior, add optional: true to the belongs_to declaration.

Upvotes: 4

Related Questions