ruby-on-rails – 为什么我在Rails模型回调中得到这个“未定义的
我有一个名为“Post”的类,它应该在更改或尚未转换时将其降价内容转换为
HTML.我正在尝试使用带有if:参数的before_save回调,但是当我尝试运行测试时,无论我传递给if,我都会收到此错误:
这是有问题的模型: class Post < ActiveRecord::Base include ActiveModel::Dirty before_save :convert_markdown,if: :markdown_changed_or_html_nil? belongs_to :user validates :user,:title,:content_markdown,{ presence: true,on: create } validates_associated :user protected def convert_markdown markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,space_after_headers: true,underline: true) self.content_html = markdown.render(content_markdown) end def markdown_changed_or_html_nil? content_markdown.changed? || content_markdown.nil? end end 我正在使用Ruby 2.0.0和Rails 4.0.2. 我可能已经犯了一个非常基本的错误 – 我还在学习Rails. 编辑:这是post_test.rb require 'test_helper' class PostTest < ActiveSupport::TestCase test 'saving an empty object fails' do new_post = Post.new assert_not new_post.save end test 'validates that given user id corresponds to user' do # This will create a user with a given id so we can use the next one up test_user = User.create({ name: 'Johnny Test',email: 'johnny.test@example.com',password: 'password',password_confirmation: 'password' }) # Use next id up - there's no reason it should be taken at this point given_user_id = test_user.id + 1 post_with_invalid_user = Post.new({ title: 'Look at my glorious title',content_markdown: 'Sick content',user_id: given_user_id }) assert_not post_with_invalid_user.save end test 'converts markdown into html' do # This is a really really basic test just to make sure a conversion happens new_post = Post.new({ title: 'Check out this markdown,baby',content_markdown: 'I got some *sick* markdown',user_id: users(:paul).id }) assert_equal '<p>I got some <em>sick</em> markdown</p>',new_post.content_html end end 解决方法
这可能不是您的主要问题(因为您的错误消息似乎与它无关),但您没有使用更改?正确.改变了吗?需要在模型对象上调用,可选地以您的属性名称为前缀.所以你的条件方法应该是这样的:
def markdown_changed_or_html_nil? # based on your method name,shouldn't this be: # content_markdown_changed? || content_html.nil? content_markdown_changed? || content_markdown.nil? end 在http://api.rubyonrails.org/classes/ActiveModel/Dirty.html找到有关Dirty方法的更多信息. 也 我很确定Rails 4没有将Dirty移出ActiveRecord :: Base,因此您不需要在模型中手动包含ActiveModel :: Dirty. 也 这一行: validates :user,on: create } 应该: validates :user,on: :create } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |