Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 错误消息不';不能在HTML ruby代码中工作_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 4 错误消息不';不能在HTML ruby代码中工作

Ruby on rails 4 错误消息不';不能在HTML ruby代码中工作,ruby-on-rails-4,Ruby On Rails 4,我使用的是rails 4.1.6,我查看了活动记录验证站点并按照它们的指示进行操作,但是HTML中没有显示任何内容,即使有错误 但是,当我在rails控制台中执行此操作时,它会正常工作 post = Post.new #create an empty post to test post.valid? #false post.errors.messages #this is successfully generate the error message array 但是,它不会在HTML中显示任

我使用的是rails 4.1.6,我查看了活动记录验证站点并按照它们的指示进行操作,但是HTML中没有显示任何内容,即使有错误

但是,当我在rails控制台中执行此操作时,它会正常工作

post = Post.new #create an empty post to test
post.valid? #false
post.errors.messages #this is successfully generate the error message array
但是,它不会在HTML中显示任何错误消息。事实上“@post.errors”甚至没有运行

-html中的Ruby代码

<%= form_for @post, :method => :post do |f| %>

  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :url %>
  <%= f.text_field :url %>

  <%= f.submit "Submit" %>

  <% if @errors.any? %>
    <ul>
      <% @errors.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  <% end %> 
<% end %>
-我的后模特

class Post < ActiveRecord::Base
  validates :title, :length => {maximum: 140, minimum:1}, :presence => true
  validates :title, :length => {maximum: 2083, minimum:1}, :allow_blank => true
end
class Post{最大值:140,最小值:1},:presence=>true
验证:title,:length=>{最大值:2083,最小值:1},:allow_blank=>true
结束

谢谢您的帮助。从我的老师那里得到了一些关于这项工作的建议。只需使用flash[:message]就可以了。对不起,给大家添麻烦了

-我的控制器代码

def create
  post = Post.new(post_params)
  if post.save
    redirect_to :back
  else
    flash[:message] = post.errors.messages
    redirect_to :back
  end
end
-我的HTML代码

<%= simple_form_for @post, :method => :post do |f| %>

  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :url %>
  <%= f.text_field :url %>

  <%= f.submit "Submit" %>
  <%= flash[:message] %>

<% end %>
:post do | f |%>

当遇到错误时,我确实希望有一个部分错误,这样我就可以在整个应用程序中保持错误不变,如下所示:

app/views/shared/\u errors.html.erb:

<% if object.errors.any? %>
 <h5>The <%= t("activerecord.models.#{object.class.to_s.downcase}") %> could not be saved due to the following errors:</h5>

      <ul>
        <% object.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
      <% end %>
      </ul>
<% end %>

由于以下错误,无法保存:
然后,对于要显示错误的视图,只需调用:

<%= render 'shared/errors', object: @your_object %> 

希望这有帮助

<%= render 'shared/errors', object: @your_object %>