collection_select with one-to-many / many-to-many

问题描述 投票:2回答:1

如何在一对多对一的情况下使用collection_select。这就是我所拥有的

该应用程序管理项目。每个项目都支持不同的语言集。人们现在可以使用项目支持的一种语言在项目中发布消息。

简化的类结构:

class Project < ApplicationRecord
  has_many :languageprojects
  has_many :languages, through: :languageprojects
end

class Language < ApplicationRecord
  has_many :languageprojects
  has_many :projects, through: :languageprojects
  def to_s
    language
  end
end

class Languageproject < ApplicationRecord
  belongs_to :language
  belongs_to :project
end

class Projectmessage < ApplicationRecord
  belongs_to :language
  belongs_to :project
end

如何在用户输入新消息的表单中格式化collection_select(Projectmessage)。用户必须能够选择项目支持的语言之一。

我想以用户的母语显示语言名称,因此语言以格式的表LANGUAGES存储

en
fr
ru

然后我将这些语言的翻译保存在en.yml,fr.yml,ru.yml下的locales文件夹中。例如。:

en:
  language_en: English
  language_fr: French
  language_ru: Russian

我到目前为止:

<%= form.collection_select :language_id, Languageproject.all, :id, :language, { include_blank: false }, { class: 'form-control' } %>

这显示了表条目的值(即en,fr,ru)。如何整合语言翻译?我希望下拉菜单显示英语,法语,俄语

显然我总是可以编码而不是使用'collection_select',但我希望有一种“Ruby”方式来解决这个问题。

ruby-on-rails
1个回答
1
投票

尝试使用options_for_select

<%= f.select :language_id, options_for_select(@language_project.languages.all.map{|l| [l.language, l.id]}, @language.id), include_blank: false, class: 'form-control' %>
© www.soinside.com 2019 - 2024. All rights reserved.