在Rails中将记录从一种模型转移到另一种模型?

时间:2019-12-03 08:29:13

标签: ruby-on-rails mongoid

我使用Ruby on Rails 5.2.3,Mongoid 7

我必须对用户和个人资料进行建模,并且需要将:名称:image_url 从用户转移到个人资料,并且在某些记录中有空白字段。

User.rb

class User
  include Mongoid::Document

  field :name, type: String
  field :image_url, type: String

  has_many :profiles, dependent: :destroy
end

Profile.rb

class Profile
  include Mongoid::Document

  field :name, type: String
  field :image_url, type: String

  belongs_to :user, touch: true
end

我正在尝试这样做,但出现错误。

如果记录中没有图像,我会得到

  

NoMethodError(nil:NilClass的未定义方法“路径”)

如果记录中没有名称或图像,则不应创建模型,但应创建模型

def set_profile
    if self.name || self.image_url != nil
      Profile.create!(
        :user_id => self.id,
        :name => self.name,
        :image_url => Cloudinary::Utils.cloudinary_url(self.image_url.path, { size: '100x100', crop: :thumb, dpr: 3.0 })
      )
    end
  end

0 个答案:

没有答案