2016-03-17 2 views
1

Это моя модель изображения:Создать модель, которая BELONGS_TO другой в Rails 5

class Image < ApplicationRecord 
    belongs_to :user 

    mount_uploader :avatar, AvatarUploader 
end 

Я не могу даже создать изображение в консоли без пользователя? Изменилось ли это с 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>]> 

я не могу получить мою установку фабрики:

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 

Это мои ошибки 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 

ответ

4

Да изменяемые в рельсах 5. Если вам нужно предыдущее поведение, добавить optional: true для объявления belongs_to.