Rails select 来自数据库

Rails select from database

有人可以解释一下吗? , 来自 ruby 指南

<%= collection_select(:person, :city_id, City.all, :id, :name) %>

我有一个附件模型,我想在创建对象时 select 它的带有组合框的版本,我还想要一个新的版本选项。

here what attachment has

def change
create_table :attachments do |t|
  t.string :filename
  t.attachment :file
  t.string :version
  t.text :description
  t.timestamps null: false
end

UPDATE:

<%= f.collection_select( :version,  Attachment.where.not(version: nil), :version, :version) %>

它是这样工作的,但我不明白,

检查此线程中已接受的答案以了解 collection_select 的工作原理:Can someone explain collection_select to me in clear, simple terms?

在这个select中:

<%= collection_select(:f, :attachment_id, Attachment.all, :id, :version) %> 

您显示已创建附件的所有版本,因此如果附件 table 为空,您将得到 null

试试这个来避免 versionnil 值:

collection_select(:f, :attachment_id, Attachment.where.not(version: nil), :id, :version)

collection_select 工作原理说明:

collection_select(
    :f, # field namespace 
    :attachment_id, # field name
    # result of these two params will be: <select name="f[attachment_id]">...

    # then you should specify some collection or array of rows.
    # In your example it is:
    Attachment.where.not(version: nil)

    # Then, you should specify methods for generating options
    :id, # this is name of method that will be called for every row, result will be set as key
    :version # this is name of method that will be called for every row, result will be set as value
)

有关详细信息,请参阅 this and this