gpt4 book ai didi

ruby-on-rails - ruby rails : Why a select box does not show the current object value?

转载 作者:行者123 更新时间:2023-12-04 06:25:57 24 4
gpt4 key购买 nike

这是来自views/products/edit.html.erb的相关代码:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<%= submit_tag("Update Product") %>
<% end %>

来自views/products/_form.html.erb:

<%= select_with_new_option(f, :shop, :name, :id) %>

来自helpers/products_helper.rb:

def select_options_with_create_new(objects, text_field, value_field, options={})
object = objects.to_s.singularize
all_objects = object.capitalize.constantize.all
all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by)
select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] }
select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"]
options_for_select(select_options)
end

def wrap_create_new_option(str)
">> #{str} <<"
end

# By default, sorts by 'text_field'.
def select_with_new_option(f, object, text_field, value_field)
f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field))
end

我希望选择框默认为 @product.shop_id,但这不是真的(第一个选项始终是默认值)。

我错过了什么?

最佳答案

好的,我知道了。只需删除 select_options_with_create_new 方法中的 options_for_select(select_options)

options_for_select 将二维数组 select_options 组装成一串 html 选项,它被 select 表单助手接受,但是,而不分配 selected 属性。只需将二维数组作为第二个参数传递给 select 方法,它会自动分配 selected

关于ruby-on-rails - ruby rails : Why a select box does not show the current object value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4436267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com