【问题标题】:How to set a value of a text field if an instance variable is not null in rails如果实例变量在rails中不为空,如何设置文本字段的值
【发布时间】:2017-02-24 16:45:43
【问题描述】:

我有一个新的产品表单,在此表单中,我将通过转到 products/new 或通过在按下按钮时传入一个实例变量来使用来自“特征的实例变量。

该代码在大部分情况下都有效,我可以毫无错误地填充表单,但我目前将文本字段的 value 属性设置为 nil 或预填充的值。如果我收到任何错误,表单将重新加载,并将任何现有字段的值设置为 nil,我的文本字段代码是:

<%= form_for @product, remote: true, html: { class: 'form-horizontal' } do |f| %>
  <%= f.text_field :name, 
          class: 'form-control', 
          value: @feature.nil? ? nil : @feature.primary_name %>
<% end %>

我想知道是否有一种简单的方法可以仅在 @feature 的情况下设置此值 变量有值,所以不是将值设置为 nil,而是根本不触及该值。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    我会在控制器中设置该值:

    # in products_controller.rb
    def new
      @feature # I assume @feature is assigned at this point
      @product = Product.new
      @product.name ||= @feature.try(:primary_name)
    end
    
    # and a plain view without special logic
    <%= f.text_field :name, class: 'form-control' %>
    

    另一种选择可能是在 Product 上使用一个特殊方法,该方法返回一个新的 Product 并设置值:

    # in product.rb
    def self.new_from_feature(feature)
      feature ? new(name: feature.primary_name) : new
    end
    
    # in products_controller.rb
    def new
      @feature # I assume @feature is assigned at this point
      @product = Product.new_from_feature(@feature)
    end
    
    # and a plain view
    <%= f.text_field :name, class: 'form-control' %>
    

    【讨论】:

      【解决方案2】:

      编辑

      随着问题的改变,这是新的答案。

      在这种情况下,您将不得不手动执行此操作,但您仍然可以通过将其更改为以下条件来避免这种情况

      <%= f.text_field :name, 
            class: 'form-control', 
            value: @feature.try(:primary_name) %>
      

      如果您使用的是 ruby​​ 2.3.0 及更高版本,您还可以使用 安全导航运算符

      @feature&.primary_name
      


      旧答案

      如果您正确使用表单助手,则无需手动设置该值。

      <%= form_for @product do |f| %>
      
        <%= f.text_field :primary_name, class: 'form-control' %>
      

      :name 更改为:primary_name 即可解决问题

      确保在 newedit 操作中正确初始化变量 @product

      def new
        @product = Product.new
      end
      
      def edit
        @product = Product.find(params[:id])
      end
      

      如果调用new 操作,文本字段将为空,但如果调用编辑操作,则@product.primary_name 的值将出现在文本字段中

      【讨论】:

      • 抱歉,我的问题不够清楚,我将一个“功能”实例变量传递给产品/新表单,这就是为什么我使用不同的值表单的标签 - 编辑了问题
      • 会||或 ||= 运算符在这里有用吗?
      • 是的,你可以使用||,但无论如何你会得到nil,所以try更好
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2015-03-25
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多