当我从轨道上的红宝石中保存多个选择时,它似乎在前面添加了一个空白元素。我该如何删除它?该字段是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
答案 0 :(得分:15)
这适用于空字符串:
array.delete_if(&:empty?)
要过滤掉空字符串和nil值,请使用:
array.delete_if(&:blank?)
示例:
>> a = ["A", "B", "", nil]
=> ["A", "B", "", nil]
>> a.delete_if(&:blank?)
=> ["A", "B"]
答案 1 :(得分:6)
Array类的参考reject!
params["schedule"]["selected_players"] = ["", "38", "41"]
params["schedule"]["selected_players"].reject!{|a| a==""} #gives params["selected_players"] = ["38", "41"]
答案 2 :(得分:1)
这应该也可以。
params["schedule"]["selected_players"].reject!(&:blank?)
答案 3 :(得分:0)
类似的东西:
params["selected_players"].select!{|val| !val.empty?}
应该有效
答案 4 :(得分:0)
什么是“selected_players”?它是否类似于集合关联的“collection_singular_ids”?如果是这样,您可以保持原样,因为ActiveRecord将使用以下代码从数组中删除空白元素:
ids = Array.wrap(ids).reject { |id| id.blank? }
答案 5 :(得分:0)
如果你想在模型而不是控制器中处理这个问题,你可以添加一个像这样的setter方法
def selected_players=(param_array)
write_attribute(:selected_players, param_array.reject(&:blank?))
end
答案 6 :(得分:-2)
我认为params["selected_players"].compact
是最简洁的。
文档在这里:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-compact