Search code examples
ruby-on-railsrubyruby-on-rails-5erblink-to

Rails how to use link_to for an external website and also using a block?


I am trying to use link_to with block and also to link with an external web site, I already know how to use link_to to make my div clickable (learned from here) and also to use link_to to send user to another website (learned from here) but when I try to combine this two approches I got an error:

undefined method 'stringify_keys' for "www.google.com":String

Here is my html.erb code:

<%= link_to @slides[0].link, "#{@slides[0].link}", target: "_blank"  do %>
  <div class="carousel-item active">
    <%= image_tag @slides[0].slide_image.thumb.url, class: "d-block w-100", alt: @slides[0].image_text %>
    <div class="carousel-caption d-none d-md-block">
      <h5><%= @slides[0].image_text %></h5>
    </div>
  </div>
<% end %>

I also tried:

<%= link_to @slides[0].link do %> # or
<%= link_to "#{@slides[0].link}", :target => "_blank" do %>
# I got the same error

<%= link_to url_for(@slides[0].link) do %>
# above I got localhost:3000/https://google.com insted of https://google.com

Does anyone know how to do this?


Solution

  • The link_to with block works like this:

    link_to(url, html_options = {}) do
      # block
    end
    

    link_to helper source

    So you just have to do :

    <%= link_to @slides[0].link, target: "_blank"  do %>
      #block
    <% end %>
    

    (assuming @slides[0].link == "https://google.com" i.e valid external url)