【问题标题】:Rails: How to use select in formtastic with activeRecordRails:如何在 formtastic 中使用 select 和 activeRecord
【发布时间】:2010-08-17 17:09:03
【问题描述】:

我是 Rails 新手,我想你可以轻松回答这个问题。

到目前为止我得到的是

= f.input :task, :as => :select, :collection => @tasks, :include_blank => true

任务集合的定义位置

Task.find(:all)

在控制器中。

这确实有效,向我显示了所有任务的下拉列表以供选择并连接它们。 这里的问题是,下拉菜单会显示像

这样的值
#<Task:0x123456789d1234>

在哪里定义要显示的值?

【问题讨论】:

    标签: ruby-on-rails select formtastic


    【解决方案1】:

    相信你可以使用:label_method来解决你的问题...

    f.input :task, :as => :select, :collection => @tasks, 
       :include_blank => true, :label_method => :title
    

    :title 是您要显示的内容。

    This 可能会有所帮助。

    【讨论】:

    • 非常感谢您,您发布的链接效果很好。只需要在模型类中实现一个“to_label”函数
    【解决方案2】:

    你可以在模型中定义一个to_s方法:

    class Task < ActiveRecord::Base
    
      def to_s
        title # the attribute to display for the label
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多