【问题标题】:Simple Form label_method for associated model关联模型的简单表单 label_method
【发布时间】:2026-02-23 11:30:01
【问题描述】:

我有一个使用 slim/simple_form 的表单。

= f.association :users,
  collection: @users,
  prompt: "Choose Recipient",
  label_method: :first_name

我想将用户的全名作为标签方法,有人能指出我正确的方向吗?我只有 first_name 和 last_name 作为属性。为了便于选择,我更愿意在全名旁边添加用户的公司名称。简单的形式允许这样做吗?否则我将退回到选择集合中的选项

【问题讨论】:

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


    【解决方案1】:

    在你的模型上创建一个方法:

    class User < ArcitveRecord::Base
      # ...
    
      def full_name
        "#{first_name} #{last_name}"
      end
    end
    

    并使用它:

    = f.association :users,
      collection: @users,
      prompt: "Choose Recipient",
      label_method: :full_name
    

    【讨论】:

    • 我实际上已经在模型中使用了它。傻我没想用它,我以为只有数据库属性可用
    【解决方案2】:

    如果您喜欢在full_name 旁边添加company_name,我只需将Broisatse 的 答案修改为

    class User < ArcitveRecord::Base
      # ...
    
      def full_name_with_company_name
        "#{first_name} #{last_name} #{company_name}"
      end
    end
    

    并使用它:

    = f.association :users,
      collection: @users,
      prompt: "Choose Recipient",
      label_method: :full_name_with_company_name
    

    【讨论】: