aforalegria
aforalegria

Reputation: 370

iterating over array inside "select" helper

I have selector in edit form which should assing User to Project.

= f.label :user_id
= f.select(:user_id, [['First user', 1], ['Second user', 2]])

Now it's with sample data.

User model should parse user.name and user.id of each existed user in the selector. That way I'll be able to assign required user to project

For now I have

- User.all.each do |user|
  = f.select(:user_id, [[user.name, user.id]])

But it just creates separate selector for each User. But I need to create a list of existed users in one selector. Which is the best way to display results of iteration over users? I guess there should be %li tag but I can't figure out how to implement it correctly.

Upvotes: 0

Views: 134

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

To use f.select as you wish you could use pluck:

= f.select(:user_id, User.pluck(:name, :id))

User.pluck(:name, :id) creates an array of [name, id] tuples.

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

If I understood you correctly, you can use collection_select helper:

f.collection_select(:user_id, User.all, :id, :name)

Upvotes: 1

Related Questions