我有一个新的产品表单,在这种表单中,我可以通过转到 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,而是根本不会触及该值。
最佳答案
我会在 Controller 中设置该值:
# 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' %>
关于ruby-on-rails - 如果 Rails 中的实例变量不为空,如何设置文本字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42443981/