我有一个文本字段,可以输入字符串值,例如:
"games,fun,sports"
我的主要目标是将字符串转换为以下的数组:
[games, fun, sports]
在我的integrations对象的filters属性中,我有一段代码。目前我有一个似乎不起作用的方法开头。
这是我的代码:
视图:
<%= form_for @integrations, url: url_for(:controller => :integrations, :action => :update, :id => @integrations.id) do |f| %>
<%= f.label :filters %>
<%= f.text_field :filters, class: "filter-autocomplete" %>
<%= f.submit "Save" %>
<% end %>
那是接收字符串的文本字段。
模型:
def filters=(filters)
end
这是我希望从字符串转换为数组的位置。
控制器:
def update
@integrations = current_account.integrations.find(params[:id])
if @integrations.update_attributes(update_params)
flash[:success] = "Filters added"
redirect_to account_integrations_path
else
render :filters
end
end
def filters
@integrations = current_account.integrations.find(params[:id])
end
private
def update_params
[:integration_webhook, :integration_pager_duty, :integration_slack].each do |model|
return params.require(model).permit(:filters) if params.has_key?(model)
end
end
所以,简单概括一下:我有一个集成模型,它接收一串过滤器字符串。我想要一个方法,将该字符串分解为过滤器属性的元素。
以下是我尝试添加过滤器的对象:
对象:
id: "5729de33-befa-4f05-8033-b0acd5c4ee4b",
user_id: nil,
type: "Integration::Webhook",
settings: {"hook_url"=>"https://hooks.zapier.com/hooks/catch/1062282/4b0h0daa/"},
created_at: Mon, 29 Aug 2016 03:30:29 UTC +00:00,
owner_id: "59d4357f-3210-4ddc-9cb9-3c758fc1ef3a",
filters: "[\"Hey\", \"ohh\"]">
正如您所看到的,我正在尝试修改filters
。而不是在对象中使用以下内容:
"[\"Hey\", \"ohh\"]"
I would like this:
[Hey, ohh]
games
、fun
、sports
、Hey
和ohh
是变量,否则[games, fun, sports]
和[Hey, ohh]
将是非法的数组定义。 - the Tin Man