2

我正在尝试制作一个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_id(在Entries模型中),我可以在其中选择文档 id 的值。

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

models/document.rb

class Document < ApplicationRecord
  has_many :Entries
end

models/entry.rb

class Entry < ApplicationRecord
  belongs_to :Documents
end

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

4

3 回答 3

5
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 %>
于 2016-08-12T08:31:24.517 回答
1

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

当您使用时,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 是包含所有文档的保险变量。

谢谢

于 2016-08-12T08:12:33.560 回答
0

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

<%= f.select :document_id, entry.documents, include_blank: true %>
于 2017-11-04T23:27:02.973 回答