我一直在寻找同样的问题,但没有找到它。
我正在关注此guide,我一直在为文本字段设置验证。
模型(article.rb):
class Article < ActiveRecord::Base
validates :title, presence: true, length: { minimum: 5 }
end
控制器:
class ArticlesController < ApplicationController:
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
查看(new.html.erb):
<%= form_for :article, url: articles_path do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', articles_path %>
当我尝试添加新文章时,我会打开http://localhost:3000/articles/new
,但由于此行中的错误undefined method errors' for nil:NilClass
<% if @article.errors.any? %>
我在这里缺少什么。看起来@article
在创建之前正在验证?我该如何解决?
index.html.erb:
<h1>Listing articles</h1>
<%= link_to "New article", new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
</tr>
<% end %>
</table>
答案 0 :(得分:0)
您需要致电:
HttpCookie cookie = new HttpCookie("User");
cookie.Values["UserType"] = usertype;
cookie.Expires = DateTime.MaxValue;
HttpContext.Response.SetCookie(cookie);
在new.html.erb的第一行
答案 1 :(得分:0)
将form_for
更改为
<%= form_for(@article) do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
........
<% end %>
articles_controller.rb
class ArticlesController < ApplicationController
....
end