在Rails字段中处理多个逗号分隔值

时间:2013-05-07 22:12:00

标签: ruby-on-rails ruby

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

# 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"