【问题标题】:How can I make a form remember the input for a virtual attribute?如何让表单记住虚拟属性的输入?
【发布时间】:2014-04-05 18:18:43
【问题描述】:

在我看来,我有

<%= form_for(@post) do |f| %>
    <%= f.text_field :name %>
    <%= f.text_field :tag_list %>
    <%= f.submit %>
<% end %>

其中 tag_list 是一个虚拟属性。

class Post < ActiveRecord::Base
  def tag_list
    #Virtual attribute stuff
  end

  def tag_list=(value)
    #Virtual attribute stuff
  end
end

问题是当用户提交表单并且它没有通过验证时,表单不记得 tag_list 字段的输入。它只记住名称字段的输入。如何让表单记住 tag_list 的输入?

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4


    【解决方案1】:

    当您在控制器操作中获得表单参数时,将其保存在会话中。

    示例:

    def new
      @post = Post.new
      @tag_list = session[:tag_list]
    end
    
    session[:tag_list]= params[post][tag_list]
    @post = params[post]
    
    if @post.save 
      ...
    else 
      ...
    end
    

    现在在您的表单中,使用 @tag_list 填充 tag_list

    <%=f.text_field, :tag_list, @tag_list%>
    

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      相关资源
      最近更新 更多