【问题标题】:Ruby on Rails: Why a select box does not show the current object value?Ruby on Rails:为什么选择框不显示当前对象值?
【发布时间】:2011-05-25 02:09:30
【问题描述】:

这是来自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,但事实并非如此(第一个选项始终是默认值)。

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails forms select ruby-on-rails-3


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我认为,在这种情况下,您需要做的就是确保在您的 edit 操作中设置 @product

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

      然后改变你的第一行:

      <%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
      

      <%= form_for(@product, :url => {:action => 'update', :id => @product.id}) do |f| %>
      

      第一个代码块肯定会更新正确的产品,但只有当您生成 form_for @product 并设置了 @product 变量集时,您才会看到反映的当前值。

      【讨论】:

      • 我在edit 方法中设置了@product,就像你写的一样。我还尝试将:product 更改为@product,但没有帮助。你有什么其他想法可能是错的吗?
      • @product.id 和 obj.send(value_field) 是同一类型吗?如果一个是整数,一个是字符串,可能会导致您看到的问题。需要注意的另一件事是,如果您刷新页面并且选择框中当前选择的选项发生更改,某些浏览器不会显示更改,因此测试这些更改可能具有欺骗性。
      • @lain: @product.id 是整数。 obj.send(value_field) 在我的例子中是 shop.send(:id),相当于 shop.id,也是整数。我相信浏览器不是这里的问题。我使用最新的 Firefox。
      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多