Ramazan Zor
Ramazan Zor

Reputation: 209

Rails select from database

Can somebody explain this ? , it is from ruby guides

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

I have an attachment model, I want to select its version with combobox when I create an object, and also I want a new version option.

here what attachment has

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:

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

it is working like that, but I don't understand,

Upvotes: 3

Views: 1580

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

Try this to avoid the nil value of the version:

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

Explanation of How collection_select Works:

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
)

See this and this for more information.

Upvotes: 5

greg
greg

Reputation: 29

check accepted answer from this thread for explanation on how collection_select works: Can someone explain collection_select to me in clear, simple terms?

In this select:

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

you display all versions from already created attachments, so if attachments table is empty you will get null

Upvotes: 1

Related Questions