小编Joe*_*son的帖子

在ruby模型上获取错误:"除非保存父级,否则无法调用create"

所以我在我的一个模型中创建了一个方法来解析文本体中的主题标签.这是模型:

class Conversation < ActiveRecord::Base
  has_many :comments
  has_many :hashtags, as: :hashtaggable, autosave: true
  belongs_to :user
  attr_accessible :description, :title, :user_id
  before_save :create_hashtags

  private

  def create_hashtags
    if self.description_changed? || self.hashtags.empty?
      ##scan for new hashtags
      scanned_tags = self.description.scan(/#\w+/)
      ##delete old hashtag
      self.hashtags.destroy_all unless self.hashtags.empty?
      ##save the new hashtag
      scanned_tags.each do |hashtag|
        self.hashtags.create name: hashtag
      end unless scanned_tags.empty?
    end
  end

  validates :description, presence: true, length: { in: 5..400 }
  validates :title, presence: true, length: {in: 20..250}
  validates :user, presence: true
end
Run Code Online (Sandbox Code Playgroud)

如果我正在更新已经存在的"对话",这可以正常工作,但如果我尝试创建一个新对话,我会收到此错误:

    ActiveRecord::RecordNotSaved at …
Run Code Online (Sandbox Code Playgroud)

ruby activerecord ruby-on-rails models

0
推荐指数
1
解决办法
7220
查看次数

标签 统计

activerecord ×1

models ×1

ruby ×1

ruby-on-rails ×1