URL是否包含字符串

URL是否包含字符串

本文介绍了URL是否包含字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将:name 传递给_form,如何使用条件语句做一件事,如果该:name 未通过?

How can I use a conditional to do one thing if :name is passed to the _form and another thing if that :name isn't passed?

已通过:name

Started GET "/inspirations/new?inspiration%5Bname%5D=Always+trust+yourself+more+than+you+doubt+yourself" for 127.0.0.1 at 2016-11-08 01:00:44 -0500
Processing by InspirationsController#new as HTML
  Parameters: {"inspiration"=>{"name"=>"Always trust yourself more than you doubt yourself"}}

没有:name 通过:

Started GET "/inspirations/new" for 127.0.0.1 at 2016-11-08 01:16:18 -0500
Processing by InspirationsController#new as */*
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Inspiration Load (0.4ms)  SELECT  "inspirations".* FROM "inspirations" WHERE "inspirations"."id" IS NULL LIMIT 1
  Rendered inspirations/_form.html.erb (4.1ms)
  Rendered inspirations/new.html.erb within layouts/modal (5.9ms)
Completed 200 OK in 49ms (Views: 41.9ms | ActiveRecord: 0.7ms)

_form

<%= simple_form_for(@inspiration) do |f| %>
  <%= f.text_area :name %>
  <% if params[:name].nil? %> # Should Be Triggered If No :name Is Present in URL
    etc...
  <% end %>
<% end %>

例如,当URL包含字符串时:

So for example when a URL includes a string:

http://www.livetochallenge.com/inspirations/new?inspiration%5Bname%5D=Life+would+be+eaisier+if+I+had+the+source+code。

但是我经常使用URL缩短器。

But I often use a URL shortener.

不适用于我:




  • Is there a way to check if part of the URL contains a certain string
  • including url parameters in if statement

推荐答案

尝试一下:

<%= simple_form_for(@inspiration) do |f| %>
  <%= f.text_area :name %>
  <% if params[:inspiration].try(:[], :name).nil? %> # Should Be Triggered If No :name Is Present in URL
    etc...
  <% end %>
<% end %>

仅当存在后者时,才检查params中的:name [:inspiration]。因此,不会发生任何错误。

This will check :name inside params[:inspiration] only if the later is present. So, no error should occur.

这篇关于URL是否包含字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:59