MKK*_*MKK 1 ruby-on-rails ruby-on-rails-3
在我的情况下,即使有验证错误,它也不会显示验证错误消息.
例如,我将这两列保留为空,并确保键入了验证字.然后,如果我尝试创建新记录.它不会显示验证错误:(它返回到表单但没有消息.
我一直在这个项目中一直使用验证错误消息,我从来没有遇到过这个问题.
任何人都可以在这里找到问题?
在主题模型中验证
validates :title,
:presence => {:message => "can't be empty" },
:uniqueness => {:message => "choose unique title" },
:length => { :maximum => 20, :message => "must be less than 20 characters" }
validates :body,
:presence => {:message => "can't be empty" },
:length => { :maximum => 500, :message => "must be less than 20 characters" }
Run Code Online (Sandbox Code Playgroud)
形成
<%= form_for([@community, @topic]) do |f| %>
.....
<%= button_tag( :class => "btn btn-primary") do %>
Create
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
topic_controller
before_filter :simple_captcha_check, :only => [:update, :create]
def simple_captcha_check
if !simple_captcha_valid?
flash[:error] = 'wrong captcha'
if request.put?
@topic.attributes = params[:topic]
render :action => :edit
elsif request.post?
@topic = Topic.new params[:topic]
render :action => :new
end
end
end
def create
@topic = @community.topics.build (params[:topic])
@topic.user_id = current_user.id
respond_to do |format|
if @topic.save
format.html { redirect_to community_topic_path(@community, @topic), notice: 'Created' }
format.json { render json: [@community, @topic], status: :created, location: @topic }
else
format.html { render action: "new" }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
的routes.rb
resources :communities do
resources :topics
end
Run Code Online (Sandbox Code Playgroud)
更新:
视图/布局/ application.html.erb
.....
<% flash.each do |name, msg| %>
<div class="alert alert-<%= name == :notice ? "success" : "error" %>">
<a class="close" data-dismiss="alert">×</a>
<%= content_tag :div, msg, :id => "flash_#{name}" if msg.is_a?(String) %>
</div>
<% end %>
.....
Run Code Online (Sandbox Code Playgroud)
Flash在下一个请求之前不会出现.因此,如果您正在进行"重定向",则会出现.
但是,您正在进行渲染而不是重定向.渲染时,返回视图本体.
但不用担心,如果你想渲染一个视图(这很好),使用像这样的闪存 -
flash.now[:error] = 'wrong captcha'
Run Code Online (Sandbox Code Playgroud)
.now确保在同一请求中的渲染视图中刷新闪存.
编辑:
您的验证没有出现的原因(当验证码失败时)是因为您的before_filter确实呈现并停止甚至被调用的创建操作.@topic验证仅在create中的@ topic.save触发,但由于永远不会被调用(当验证码失败时),因此不会出现与属性验证相关的任何内容.
其次,flash.now [:error]将确保flash消息不会转移到下一个请求,因为您打算在同一请求的响应中使用.但是,如果你设置了flash [:error]和render,那么你的flash消息将出现在同一个请求的响应和下一个请求中.这应该回答@ saurabh上面的好问题并解开谜团?
最终编辑:@MKK必须包含一个错误,显示视图中缺少的部分内容.