Ruby on Rails:为什么选择框不显示当前的对象值? [英] Ruby on Rails: Why a select box does not show the current object value?

查看:154
本文介绍了Ruby on Rails:为什么选择框不显示当前的对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 views / products / edit.html.erb 中的相关代码:

Here is the relevant code from 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 %>

from views / products / _form.html.erb

from 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 ,但这不是真的(第一个选项始终是默认值)。

I expect the select box to be @product.shop_id by default, but this is not true (the first option is always the default value).

我缺少什么?

推荐答案

好的,我明白了。只需在 select_options_with_create_new 方法中删除 options_for_select(select_options)

Alright, I got it. Just remove options_for_select(select_options) in the select_options_with_create_new method.

options_for_select 将二维数组 select_options 组合成html选项的字符串, code> select 表单助手,但是不分配选定的属性。只需将二维数组作为第二个参数传递给选择方法,它将自动分配选定的

The options_for_select assembles the 2-d array select_options into a string of html options, which is accepted by the select form helper, however, without assigning the selected attribute. Just pass the 2-d array to the select method as the second argument, it would assign the selected automatically.

这篇关于Ruby on Rails:为什么选择框不显示当前的对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆