加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails:为什么选择框不显示当前对象值

发布时间:2020-12-17 01:21:42 所属栏目:百科 来源:网络整理
导读:以下是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 / produc
以下是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,value_field)
  f.select(:"#{object}_id",select_options_with_create_new(object.pluralize,:order_by => text_field))
end

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

我错过了什么?

解决方法

好吧,我明白了.只需删除select_options_with_create_new方法中的options_for_select(select_options)即可.

options_for_select将2-d数组select_options组装成一个html选项字符串,但是,select表单帮助程序可以接受它,但不指定所选属性.只需将2-d数组作为第二个参数传递给select方法,它就会自动分配所选的数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读