1

我在应用程序中有一个字段,当前允许组管理员邀请其他用户(加入组)。它适用于单个值,但我想知道如何调整它,以便它允许管理员在字段中输入多个用逗号分隔的用户。

# 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
4

2 回答 2

1

尝试这个:

<%= 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
于 2013-05-07T22:29:11.100 回答
0

你可以让params[:user_name]一个逗号分隔的用户列表并在invite_user中解析它:

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

这将拆分params[:user_name]为一个数组,以逗号分隔,后跟零个或多个空白字符。变成. "Joe, John, Marry,Ann"_["Joe", "John", "Marry", "Ann"]

然后,您仍然可以在邀请用户中执行以下操作:

@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"
于 2013-05-07T22:23:09.740 回答