在这个例子中,我创建了一个user没有profile,然后在profile为该用户创建一个.我尝试使用带有has_one关联的构建,但是爆炸了.我看到这个工作的唯一方法是使用has_many.本user应该只有最多只能有一个profile.
我一直在尝试这个.我有:
class User < ActiveRecord::Base
  has_one :profile
end
class Profile < ActiveRecord::Base
  belongs_to :user
end
但当我这样做时:
user.build_profile 
我收到错误:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4)  LIMIT 1
在rails中有一种方法可以有0或1个关联吗?
Organization并Image有一个1-to-1 relationship.Image有一个名为的列filename,它存储文件的路径.我有一个包含在资产管道中的文件:app/assets/other/image.jpg.播种时如何包含此文件的路径?
我试过我的种子文件:
@organization = ...
@organization.image.create!(filename: File.open('app/assets/other/image.jpg'))
# I also tried:
# @organization.image.create!(filename: 'app/assets/other/image.jpg')
两者都生成错误:
NoMethodError: undefined method `create!' for nil:NilClass
我检查了debugger并且可以确认它不是 @organization零.
如何使这项工作并将文件的路径添加到Image模型中?
更新:我尝试了以下内容:
@image = Image.create!(organization_id: @organization.id,
                       filename: 'app/assets/other/image.jpg')
我也尝试过:
image = @organization.build_image(filename: 'app/assets/other/image.jpg')
image.save
播种后,两次尝试都会产生错误:
CarrierWave::FormNotMultipart: You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.