Frage

I'm working on a way to construct a guest list of an event called a Party. The user_id of each invited guest is stored in a hidden field, separated by spaces.

<%= hidden_field_tag 'guestlist', nil, :class => 'guest_list' %>

When a user invites a new guest, the guest's id is added to the field and stored.

I'm trying to figure out a way so that when a User edits an existing party, the id's of the already invited guests show up in the hidden guest_list field.

Is there a way to do this with embedded Ruby? Something along the lines of:

<% @party.guests.each do |guest| %>
 Do something here
<% end %>
War es hilfreich?

Lösung

Try this (in 2 steps for readability):

<% guest_ids = @party.guests.map(&:id).join(",") %>
<%= hidden_field_tag 'guestlist', guest_ids, :class => 'guest_list' %>

The first line will call .id on each guest and then collect them in an array (like [1, 4, 12]) and then the .join will put them in to a string where it will use the "," to separate them.

EDIT The .map(&:id) is the same as saying:

@part.guests.map do |guest|
    guest.id
end

But it's condensed in to that &:id. The .id is obviously the method name we want to call and whose results we want to collect, and the & basically converts that in to a block. You can read this for some more information, or perhaps better, this SO post.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top