错误后保留表单字段(RoR)

validation后,我收到一个错误,然后我又回到了:action => :new 。 表单上的某些字段已经填满,所以即使在出现错误消息之后我也要保持填充。 怎么做?

您的视图(new.html.erb)类似于以下内容

 <%= error_message_for :user %> <% form_for :user, :action=>"create" do|f|%> <%= f.text_field :login %> <% end %> 

控制器代码(创建方法)

 def create @user=User.new(params[:user]) if @user.save redirect_to :action=>'index' else render :action=>'new' #you should render to fill fields after error message end end 

因为在我的情况下,表单是在另一个控制器视图中我使用闪存来存储我的数据,然后检查闪存中是否存在数据。 如果是,则将此值作为输入字段的默认值,如果不是只显示您想要显示的内容。

所以我的代码片段

 flash[:date] = start_date # in the view where to form resides start_day = flash[:date].nil? nil : flash[:date].day # ... <%= select day start_day ... %> 

希望能帮助你们中的一些人;-)。