新手问题 rails:render 方法渲染问题

JTAO · 2018年07月26日 · 最后由 pinewong 回复于 2018年07月27日 · 1152 次阅读

在 save 返回错误时,render 方法如何将@xxx返回原页面,保证原输入内容不变

这是 articls_controller 下

def 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 表单下

<%= form_for :article do |f| %>
  <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 %>

提交 new 表单,当 article.save 返回错误时,render 方法返回 new,而且提交的内容不变

如果我将 new 表单下 <%= form_for :article do |f| %> 改为 <%= form_for :example do |f| %>

相应的将 controller 下 params.require(:article).permit(:title, :text) 改为 params.require(:example).permit(:title, :text) 那么提交的内容被清除。

这里的参数是怎么传递的呢?

controller 里的 '@article' 要跟 form_for 里的 ':example' 对上,参数就是从这里传过去的

<%= form_for :article do |f| %>

等价于

<%= form_for @article || Article.new do |f| %>

你的 create action 需要传同名的实例变量

pinewong 回复

controller 里@article 和 form_for 里:article 形式一致,实现了保留原输入信息。换为:example 反而不能实现。

JTAO 回复

原来 article 的时候,你是都保持一致,但是换成 example 时,你还有个地方没换啊

需要 登录 后方可回复, 如果你还没有账号请 注册新账号