Rails从数据库中选择

Ram*_*Zor 3 select ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

有人可以解释一下吗?,它来自红宝石指南

<%= collection_select(:person, :city_id, City.all, :id, :name) %>
Run Code Online (Sandbox Code Playgroud)

我有一个附件模型,我想在创建对象时使用combobox选择它的版本,而且我还想要一个新版本选项.

附件有什么附件

def change
create_table :attachments do |t|
  t.string :filename
  t.attachment :file
  t.string :version
  t.text :description
  t.timestamps null: false
end
Run Code Online (Sandbox Code Playgroud)

更新:

<%= f.collection_select( :version,  Attachment.where.not(version: nil), :version, :version) %>
Run Code Online (Sandbox Code Playgroud)

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

K M*_*lam 5

试试这个以避免以下nil价值version:

collection_select(:f, :attachment_id, Attachment.where.not(version: nil), :id, :version)
Run Code Online (Sandbox Code Playgroud)

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
)
Run Code Online (Sandbox Code Playgroud)

见这个和这个以获取更多信息.