1

I have a field in an app that currently allows admins of Groups to invite other Users (to the group). It works for a single value, but I'm wondering how to adjust it so that it allows the admin to enter multiple Users separated by commas into the field.

# form in view
<%= form_tag({:controller => "group_members", :action => "invite_user"}, :method => "post") do %>
  <%= hidden_field_tag 'group_id', @group.id%>
  <%= text_field_tag :user_name %>
  <%= submit_tag "Invite" %>
<% end %>

# group_members_controller
def invite_user
  @user = User.find_by_user_name(params[:user_name])
  @group_member = GroupMember.create!(:status=>"invited", :user_id=>@user.id, :group_id => params[:group_id], :token => SecureRandom.urlsafe_base64)
  redirect_to :back, notice: "#{@user.user_name} has been invited to your group"
end
3
  • Are you using autocomplete or you are writing the use id? Commented May 7, 2013 at 22:22
  • writing the user_name, sorry, the text_field_tag should be named :user_name instead of :user_id Commented May 7, 2013 at 22:24
  • Consider using autocomplete, because is hard to write all names correctly. Commented May 7, 2013 at 22:33

2 Answers 2

1

Try this:

<%= form_tag({:controller => "group_members", :action => "invite_users"}, :method => "post") do %>
  <%= hidden_field_tag 'group_id', @group.id%>
  <%= text_field_tag :users %>
  <%= submit_tag "Invite" %>
<% end %>

# group_members_controller
def invite_users
  user_names = params[:users].split(/,\s*/)
  users = User.where(name: user_names)
  group_id = params[:group_id]

  @users.each do |user|
    GroupMember.create!(:status=>"invited", :user_id=>user.id, :group_id => group_id, :token => SecureRandom.urlsafe_base64)
  end

  redirect_to :back, notice: "Users have been invited to your group"
end
Sign up to request clarification or add additional context in comments.

Comments

0

You could let params[:user_name] be a comma seperated list of users and parse it in invite_user:

@users = params[:user_name].split(/,\s*/).

This would split params[:user_name] into an array, splitting on a comma followed by zero or more whitespace characters. Turning "Joe, John, Marry,Ann" into ["Joe", "John", "Marry", "Ann"].

You could then do the following still in invite user:

@users.each do |username|
    @user = User.find_by_user_name(params[username])
    @group_member = GroupMember.create!(:status=>"invited", :user_id=>@user.id, 
                                        :group_id => params[:group_id], 
                                        :token => SecureRandom.urlsafe_base64)

end

redirect_to :back, notice: "my_message"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.