Search code examples
ruby-on-railsruby-on-rails-5anchorlink-to

Rails simple Anchor within a Link_to Block


I've seen a hundred posts on how to add anchor tags on regular links in rails, but not one for the format to use on blocks using link_to do, etc. I know I'm missing something dumb, but what should the anchor format look like on the following block of code if I wanted to always jump to the anchor on a div ID of #selected-card? any help is greatly appreciated...

index.html.erb (with the link to the 'show' page)

<%= link_to post do %>
  <%= image_tag(post.postimage_url, :alt => "logo", :style=>"box-shadow: 0px 0px 2px #ddd; margin-bottom: 8px; width: 100%; max-height: 140px;") %>
<% end %>

I've tried <%= link_to post, anchor: "selected-card" do %> and a million other things but cannot seem to get it working.

Show.html.erb (where my anchor id lives):

<div id="selected-card">
 some code here
</div>

Routes file:

Rails.application.routes.draw do

  devise_for :users

  root to: 'visitor_pages#posts'
  # root to: 'posts#index'

  resources :posts

  resources :posts do
    member do
      get :referred, :references
    end
  end

end

Solution

  • If you use an object in place of the full path, you need to embed it with the html options inside an array (source):

    <%= link_to [post, anchor: "selected-card"] do %>
      ...
    <% end %>
    <!-- generates <a href="/posts/1#selected-card">...</a> -->