aschmid aschmid - 3 months ago 31
Ruby Question

rails 5 collection select

I am trying to make a

collection_select
that I get a drop down with the values of a field from another model. I got the following 2 models:

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


I want to get a dropdown select on
document_id
(in
Entries
model), where I can select the values of the id of a document.

I got this so far but I am not sure if it is the right way

models/document.rb


class Document < ApplicationRecord
has_many :Entries
end


models/entry.rb


class Entry < ApplicationRecord
belongs_to :Documents
end


I really hope that someone can help me and as you see in the title I am using Rails 5.

Answer
class Document < ApplicationRecord
 has_many :entries
end


class Entry < ApplicationRecord
 belongs_to :document
end

In your view file like: new.html.erb

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