这是我的图像模型:
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
这些是我的错误消息:
* 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
答案 0 :(得分:4)
是的,它在rails 5中已更改。如果您需要以前的行为,请在belongs_to声明中添加optional:true。