Rails simple_form grouped_select奇怪的行为

时间:2012-05-23 12:32:57

标签: ruby-on-rails ruby-on-rails-3 simple-form

最近发生了奇怪的事情。

我有两种模式:

class Direction < ActiveRecord::Base
  has_many :specializations, dependent: :destroy
end

and

class Specialization < ActiveRecord::Base
  belongs_to :direction
end

他们都有一个名为title的字段。

我使用分组选择制作了一个表单(它没有绑定到任何模型):

= simple_form_for :some_name do |f|
  = f.input :specialization_id, collection: Direction.all,
            as: :grouped_select,
            group_method: :specializations

在我的本地机器上一切都很好。我的选择看起来像这样:

Direction1 title
  Specialization1 title
  Specialization2 title
  ...
Direction2 title
  Specialization3 title
  Specialization4 title
  ...
...

当我将它部署到登台服务器时,有一点意外。我的选择输出已经变成这样:

#<Direction:0xb02fb60>
  #<Specialization:0xaa5fb10>
  ...
#<Direction:0x991cf90>
  #<Specialization:0xb02f868>
  ...

看起来它正在调用:to_s作为标签方法(也是值方法),而不是:title

通过明确指定这些方法来解决问题:

= simple_form_for :some_name do |f|
  = f.input :specialization_id, collection: Direction.all,
            as: :grouped_select,
            group_method: :specializations,
            group_label_method: :title,
            label_method: :title,
            value_method: :id

但我想知道它为什么会发生?我不喜欢这种惊喜。 :)

一些细节:

  • 本地计算机正在运行MacOS Lion

  • 临时服务器在Debian Squeeze上

  • Ruby版本是相同的(1.9.3p194来自rvm)

  • Rails版本:3.2.3

  • 使用Capistrano进行部署

我还尝试在虚拟Debian机器上本地重现它以进行调试。但我没有成功。

有人可以告诉我发生了什么吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

我只在生产模式下有相同的行为。

= f.input(:city_id, label: 'Ciudad', :collection => Country.order(:name), :as =>     :grouped_select, :group_method => :cities, :group_label_method => :name, :label_method => :name, promt: "Por favor seleccione una ciudad", :include_blank => true, :input_html => { class: 'span4'} )

我希望获得城市ID而不是

"#<City:0x007f943d5a2de0>"

<强>更新

我添加了simple_form propety value_method :: id ,对我来说很好。

= f.input(:city_id, label: 'Ciudad', :collection => Country.order(:name), :as =>     :grouped_select, :group_method => :cities, :group_label_method => :name, :label_method => :name, promt: "Por favor seleccione una ciudad", value_method: :id, :include_blank => true, :input_html => { class: 'span4'} )

答案 1 :(得分:0)

尝试使用f.association
例如:

 = f.association :direction

您也可以在选项

中调用label_method来定义标签