【问题标题】:rails 5 collection selectrails 5 集合选择
【发布时间】:2016-12-19 04:02:37
【问题描述】:

我正在尝试制作一个collection_select,我会从另一个模型中获得一个包含字段值的下拉列表。我有以下 2 个模型:

Documents:

class CreateDocuments < ActiveRecord::Migration[5.0]
  def change
    create_table :documents do |t|
      t.string :etiquette_number
      t.string :etiquette_type
      t.boolean :important
      t.string :work_text
      t.integer :user_id


      t.timestamps
    end
  end
end

Entries:

class CreateEntries < ActiveRecord::Migration[5.0]
  def change
    create_table :entries do |t|
      t.integer :document_id
      t.integer :user_id
      t.string :work
      t.date :date
      t.integer :time

      t.timestamps
    end
  end
end

我想在document_idEntries 模型中)上获得一个下拉选择,我可以在其中选择文档的 id 值。

到目前为止我得到了这个,但我不确定它是否是正确的方法

models/document.rb

class Document < ApplicationRecord
  has_many :Entries
end

models/entry.rb

class Entry < ApplicationRecord
  belongs_to :Documents
end

我真的希望有人可以帮助我,正如您在标题中看到的那样,我正在使用 Rails 5。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-5 collection-select


【解决方案1】:

您需要将文档范围限定为属于该条目的文档

<%= f.select :document_id, entry.documents, include_blank: true %>

【讨论】:

    【解决方案2】:

    你应该使用如下代码的关联

    当您使用has_many 时,型号名称应为plural

    class Document < ApplicationRecord
      has_many :entries
    end
    

    当您使用belongs_to 时,型号名称应为singular

    class Entry < ApplicationRecord
      belongs_to :document
    end
    

    你可以像下面这样在entry 中写选择标签

     @documents = Document.all
    
     <%= f.select :document_id, @documents.collect { |d| [ d.name, d.id ] }, include_blank: true %>
    

    @documents 是包含所有文档的保险变量。

    谢谢

    【讨论】:

    • 啊,谢谢。你现在如何在前端(如 html 选择)中使用 document_id 字段中的文档 id 的值来显示它?
    • 您可以在视图而不是文档中显示entries 列表。因为你有Document has_many :entries这样的关系。
    • 好的没问题。认为我的回答有点不清楚.. 抱歉
    • 我收到此错误:nil:NilClass 的未定义方法 `collect'
    • 您必须在控制器操作中添加 @documents 变量。即文档 = Document.all
    【解决方案3】:
    class Document < ApplicationRecord
     has_many :entries
    end
    
    
    class Entry < ApplicationRecord
     belongs_to :document
    end
    

    在您的视图文件中,例如:new.html.erb

     <%= f.select :document_id, Document.all.collect { |p| p.id }, include_blank: true %>
    

    【讨论】:

    • 我收到此错误:#<0x007ffc9d63a370>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多