If URL contains string?

2019-07-24 20:08发布

问题:

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?

With :name passed:

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"}}

Without :name passed:

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 %>

So for example when a URL includes a string:

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

But I often use a URL shortener.

Didn't work for me:

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

回答1:

Try this:

<%= 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 %>

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



回答2:

You can avoid the error using fetch.

<%= simple_form_for(@inspiration) do |f| %> 
  <%= f.text_area :name %>
  <%= f.text_area :name %>
  <% name = params.fetch(:inspiration, {}).fetch(:name, nil) %>
  <% if name.nil? %> 
    etc...
  <% end %>
<% end %>