【问题标题】:Rails select from databaseRails 从数据库中选择
【发布时间】:2015-08-20 10:12:49
【问题描述】:

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

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

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

这里有什么附件

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

更新:

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

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

【问题讨论】:

  • 试试这个 - &lt;%= collection_select(:object, : attachment_id, Attachment.all, :id, :version) %&gt;
  • 它说 undefined method `attachment_id',我认为对象是 :attachment ?从
  • 对不起,我意识到我没有 f.collection_select,我现在处理它,但我不知道如何添加新版本选项来编写不同的东西
  • 顺便说一句,我处理它,但我仍然不明白它是如何工作的
  • &lt;%= collection_select(:f, :attachment_id, Attachment.all, :id, :version) %&gt; 我认为它可以工作,但对象的版本为空

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 select


【解决方案1】:

尝试这样做以避免version 的nil 值:

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 和this 了解更多信息。

【讨论】:

    【解决方案2】:

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

    在此选择中:

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

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

    【讨论】:

    • 我可以看到1.version、2.version等选项。我可以选择但它不起作用,我刚刚创建的对象版本为空
    • 如果您使用强参数检查是否允许 f[:attachment_id],还可以考虑使用 select_tag 而不是 collection_select,因为它发送的是单个选定项目,而不是它们的数组
    • 我不明白 f[attachment_id] 是什么,我只是想从组合框中选择新的附件版本,我这样处理它&lt;%= collection_select(:f, :attachment_id, Attachment.all, :id, :version) %&gt;。但是我不知道如何写新的版本而不是从组合框中选择
    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2011-03-12
    相关资源
    最近更新 更多