Rails从数据库中选择

Rails select from database

有人可以解释吗? ,来自ruby guides

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

我有一个附件模型,我想在创建对象时使用组合框选择其版本,并且我还想要一个新的版本选项。

here what attachment has

1
2
3
4
5
6
7
8
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:

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

它正在那样工作,但我不明白,


尝试执行此操作以避免version

nil

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

collection_select的工作原理说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
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
)

有关详细信息,请参见此内容。


检查此线程接受的答案,以获取有关collection_select工作原理的解释:有人可以用清晰,简单的方式向我解释collection_select吗?

在此选择:

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

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