rails-4验证表明即使字段不是空白,字段也不能为空

时间:2014-03-11 19:36:35

标签: ruby-on-rails validation activerecord ruby-on-rails-4 liquid

我有一个带有验证的activerecord模型:body,presence:true 。填写并提交表单时,即使主体实际上不是空白,我也会 {:body => ["不能为空白"]} 。如果我从模型中删除验证并重新提交,则会成功创建记录。为什么验证说正文字段在空白时为空白。

控制器。

class SqlTemplatesController < ApplicationController

  def create
    @sql_template = SqlTemplate.new(sql_template_params)

     respond_to do |format|
        if @sql_template.save
         format.html { redirect_to @sql_template, notice: 'Sql template was successfully created.' }
    end
   end

   private
   def sql_template_params
      params.require(:sql_template).permit(:body, :path, :format, :locale, :handler, :partial)
   end

end

模特

class SqlTemplate < ActiveRecord::Base
  validates :body, :path, presence: true
  validates :format, inclusion: Mime::SET.symbols.map(&:to_s)
  validates :locale, inclusion: I18n.available_locales.map(&:to_s)
  validates :handler, inclusion: ActionView::Template::Handlers.extensions.map(&:to_s)

  def to_liquid
    SqlTemplateDrop.new(self)
  end

 def body=(text)
    if self[:handler] == 'liquid'
      @template = Liquid::Template.parse(text)
      self[:body] = Marshal.dump(@template)
    end
 end

 def render(options = {})
   template.render options
 end

 private

 def template
   return @body unless @body.nil?
   @body = Marshal.load(self[:body])
 end

end

rails控制台中如果创建新记录并将正文字段设置为字符串 body =&gt; &#34;邮件正文&#34; 或液体标记,例如正文=&gt; &#34; {{body}} ,它会引发错误 {:body =&gt; [&#34;不能为空白&#34;]} 但是如果删除他们的验证工作。

irb(main):016:0> a = SqlTemplate.create(:body => "{{body}", path => "mail/liquid_database_template", :format => "html", :locale => "en", :handler => "liquid", :partial => false)

(0.1ms)  begin transaction
(0.1ms)  rollback transaction

irb(main):016:0> a.errors.messages
 => {:body=>["can't be blank"]}

如果我删除验证并提交表单,则一切正常,如下所示:

 Started POST "/sql_templates" for 127.0.0.1 at 2014-03-11 15:28:14 +0000
  Processing by SqlTemplatesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"GVsRbsCKSlcEMiL1AzXE0tT8LBCNhhoK6wSGzvnB80A=", "sql_template"=>{"body"=>"{{body}}", "path"=>"customer_mail/liquid_database_template", "format"=>"html", "locale"=>"en", "handler"=>"liquid", "partial"=>"0"}, "commit"=>"Create Sql template"}
  #<SqlTemplate id: nil, body: nil, path: "customer_mail/liquid_database_template", format: "html", locale: "en", handler: "liquid", partial: false, created_at: nil, updated_at: nil>
 (0.1ms)  begin transaction
 SQL (9.4ms)  INSERT INTO "sql_templates" ("created_at", "format", "handler", "locale", "path", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", "2014-03-11 15:28:14.869619"], ["format", "html"], ["handler", "liquid"], ["locale", "en"], ["path", "customer_mail/liquid_database_template"], ["updated_at", "2014-03-11 15:28:14.869619"]]
 (621.4ms)  commit transaction
 Redirected to http://localhost:3000/sql_templates/7
 Completed 302 Found in 662ms (ActiveRecord: 630.9ms)

Started GET "/sql_templates/7" for 127.0.0.1 at 2014-03-11 15:28:15 +0000
  Processing by SqlTemplatesController#show as HTML
  Parameters: {"id"=>"7"}
  SqlTemplate Load (3.1ms)  SELECT  "sql_templates".* FROM "sql_templates"  WHERE  "sql_templates"."id" = ? LIMIT 1  [["id", 7]]
  Rendered sql_templates/show.html.erb within layouts/application (11.4ms)
  Completed 200 OK in 52ms (Views: 46.0ms | ActiveRecord: 3.1ms)

如果我重新添加验证并提交失败,如下所示:

Started POST "/sql_templates" for 127.0.0.1 at 2014-03-11 14:34:22 +0000
 ActiveRecord::SchemaMigration Load (0.3ms)  SELECT "schema_migrations".* FROM  "schema_migrations"
 Processing by SqlTemplatesController#create as HTML
  Parameters: {"utf8"=>"✓",  "authenticity_token"=>"GVsRbsCKSlcEMiL1AzXE0tT8LBCNhhoK6wSGzvnB80A=", "sql_template"=> {"body"=>"{{body}}", "path"=>"customer_mail/liquid_database_template", "format"=>"html",  "locale"=>"en", "handler"=>"liquid", "partial"=>"0"}, "commit"=>"Create Sql template"}
    #<SqlTemplate id: nil, body: nil, path: "customer_mail/liquid_database_template", format: "html", locale: "en", handler: "liquid", partial: false, created_at: nil, updated_at: nil>
   (0.2ms)  begin transaction
 (0.2ms)  rollback transaction
  Rendered sql_templates/_form.html.erb (32.6ms)
  Rendered sql_templates/new.html.erb within layouts/application (57.1ms)
  Completed 200 OK in 208ms (Views: 143.0ms | ActiveRecord: 1.4ms)

2 个答案:

答案 0 :(得分:1)

您的body setter在handler的设置者之前被调用。因此,self[:handler]进入body=方法

时,a = SqlTemplate.create(:handler => "liquid", :body => "{{body}", path => "mail/liquid_database_template", :format => "html", :locale => "en", :partial => false) 将为零

您可以尝试其中一种

i)更改哈希的顺序

a = SqlTemplate.new(:handler => "liquid", path => "mail/liquid_database_template", :format => "html", :locale => "en", :partial => false)
a.body = "{{body}}"
a.save

ii)设置处理程序

后稍后设置正文
{{1}}

答案 1 :(得分:0)

我自己解决了。问题在于身体场的setter方法。通常情况下,rails会自动定义这个,但是如果它被覆盖以执行一些额外的操作,那么我仍然需要在其他所有内容之前将 self [:body] = text 设置在顶部。请注意, text 是通过表单传入字段的值。如果没有,验证状态将失败。

def body=(text)
  self[:body] = text
end