【问题标题】:How can set a default value in select tag?如何在选择标签中设置默认值?
【发布时间】:2014-06-02 15:25:40
【问题描述】:

我有一张桌子,想设置默认值

这是表格:

|customers|
  |id|  |name|
    1     ABC
    2     DEF
    3     GHI
    4     JKL

这里是控制器:

@customers.Customer.all
@customer_selected =   Customer.find(:all,:conditions=>['id=1'])

这是视图,显示所有客户

<%= select_tag "customer_id", options_for_select(@customers.collect {|t| [t.name,t.id]},params[:customer_id].to_i)  %>        

我尝试这一行选择 customer_id=1 作为默认值(选中)

<%= select_tag "customer_id", options_for_select(@customers.collect {|t| [t.name,t.id]},params[:customer_id].to_i),:selected =>@customer_selected.name  %>   

我收到了这个错误

undefined method `name' for #<Array:0x7f31d8098560>    

请有人可以帮助我吗?

【问题讨论】:

  • 您指向数组中的一个元素。由于数组是元素的集合,因此您需要指定要访问的元素(在本例中为数组的第一个元素)或在数组中迭代(each、for 等)。 t[1].name, t[1].id 应该可以工作。
  • 你的控制器代码应该写成@customers = Customer.all吗?这可能是您的问题,而不是选择。

标签: ruby-on-rails ruby ruby-on-rails-2


【解决方案1】:

要记住的一件事是,如果 params[:customer_id] 不存在,那么它将等于 nil,nil.to_i 给出 0。这应该没问题,因为您不应该有一个客户id 0 但需要注意。

我认为这应该可行:

<% default_id = params[:customer_id] ? params[:customer_id].to_i : (@customer_selected && @customer_selected.id) %>
<%= select_tag "customer_id", options_for_select(@customers.collect {|t| [t.name,t.id]}, default_id)  %>        

这将使用params[:customer_id](如果已定义)或@customer_selected.id(如果已定义@customer_selected)。

【讨论】:

  • (@customer_selected &amp;&amp; @customer_selected.id) 会返回 truefalse,不是吗?在我看来,一个简单的@customed_selected.try(:id) 就足够了
  • 不,它将返回nil 或客户ID。
  • @customer_selected.try 在 Rails 2 中不起作用,我认为。
  • 哦,谢谢你的提示,不知道smth &amp;&amp; smth.id 语法; apidock.com/rails/v2.3.2/Object/try 我认为它会起作用(在我的 irb 中:Loading development environment (Rails 2.3.11)..&gt;&gt; @nothing.try(:something)..=&gt; nil
【解决方案2】:

@customer_selected 是一个数组,如错误所示。这是因为find(:all) 返回一个数组,即使只有一个结果。

你应该可以替换

@customer_selected = Customer.find(:all,:conditions=>['id=1'])

@customer_selected = Customer.find(1)

不会破坏任何东西,因为find 无论如何都会根据 ID 查找对象并返回单个记录而不是集合。

【讨论】:

  • 嗯,我刚刚注意到这个问题是关于 RoR2 的,所以我的建议可能实际上不起作用,因为我没有在那个版本中尝试过。
  • 它与 1 一起工作,但我将其替换为 2,但没有工作。 @customer_selected = Customer.find(2) 总是以 1 开头。
猜你喜欢
  • 2011-04-14
  • 2016-10-01
  • 2020-03-13
  • 1970-01-01
  • 2011-06-25
  • 2016-07-25
  • 2018-06-22
  • 1970-01-01
  • 2020-06-14
相关资源
最近更新 更多