因此,我在我的一个模型中创建了一种方法,用于解析正文中的主题标签。这是模型:
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
如果我正在更新一个已经存在的“对话”,这很好用,但是如果我尝试创建一个新的,我会收到这个错误:
ActiveRecord::RecordNotSaved at /conversations
You cannot call create unless the parent is saved
我的模型中是否缺少某些东西?我什么都试过了。