9

当我从 ruby​​ on rails 表单中保存多项选择时,它似乎在前面添加了一个空白元素。如何删除它?该字段是 selected_player。

{"utf8"=>"✓",
 "authenticity_token"=>"H8W7qPBezubyeU0adnTGZ4oJqYErin1QNz5oK0QV6WY=",
 "schedule"=>{"event"=>"1",
 "result_id"=>"",
 "time"=>"26/10/2012",
 "duration"=>"15",
 "arrival_time"=>"14",
 "location_id"=>"25",
 "selected_players"=>["", "38", "41"],
 "team_id"=>"1",
 "opponent_id"=>"7",
 "home_or_away"=>"Home"},
 "commit"=>"Save Event"}

控制器

def update
  @schedule = Schedule.find(params[:id])
  @user = User.find(current_user)
  @players = User.where(:team_id => current_user[:team_id]).all

  respond_to do |format|
    if @schedule.update_attributes(params[:schedule])
      Notifier.event_added(@user,@schedule).deliver
      format.html { redirect_to(@schedule,
                                :notice => "#{event_display_c(@schedule.event)} vs #{@schedule.opponent.name} was successfully updated.") }
      format.json { head :no_content }
    else
      format.html { render :action => "edit" }
      format.json { render :json => @schedule.errors, :status => :unprocessable_entity }
    end
  end
end
4

7 回答 7

19

这适用于空字符串:

array.delete_if(&:empty?)

要过滤掉空字符串和 nil 值,请使用:

array.delete_if(&:blank?)

例子:

>> a = ["A", "B", "", nil]
=> ["A", "B", "", nil]
>> a.delete_if(&:blank?)
=> ["A", "B"]
于 2013-12-23T15:24:26.607 回答
7

reject!Array 类的Ref

params["schedule"]["selected_players"] = ["", "38", "41"]
params["schedule"]["selected_players"].reject!{|a| a==""} #gives params["selected_players"] = ["38", "41"]
于 2012-10-24T13:18:38.303 回答
1

这也应该有效。

params["schedule"]["selected_players"].reject!(&:blank?)
于 2013-11-21T17:14:16.753 回答
0

就像是:

params["selected_players"].select!{|val| !val.empty?}

应该管用

于 2012-10-24T13:17:20.250 回答
0

什么是“selected_players”?是不是类似于集合协会的“collection_singular_ids”?如果是这样,您可以保持原样,因为 ActiveRecord 将使用以下代码从数组中删除空白元素:

ids = Array.wrap(ids).reject { |id| id.blank? }
于 2012-10-24T14:18:24.807 回答
0

If you want to handle this in the model rather than the controller you can add a setter method like this

def selected_players=(param_array)
  write_attribute(:selected_players, param_array.reject(&:blank?))
end
于 2021-06-25T01:22:09.033 回答
-3

我认为params["selected_players"].compact是最简洁的。

文档在这里:http ://www.ruby-doc.org/core-1.9.3/Array.html#method-i-compact

于 2012-10-24T14:53:56.020 回答