Rails and the <span> tag - ruby-on-rails

I'm fairly new to Ruby on Rails, and I'm attempting to create some fancy CSS buttons using the "sliding doors" technique. I have it almost working, but I feel like there has to be a better way to handle the tags for a link.
The way I'm currently doing it:
<%= link_to '<span>New car</span>', {:action => "new"}, :class=>"button" %>
This isn't terrible, per se, but I would like to know if this is the best way to handle span tags in RoR.

Another option is this:
<%= link_to content_tag(:span, 'New car'), {:action => "new"}, :class=>"button" %>
docs

Or you could be pro and use named routes/resources + Haml. That would make it look like:
%a{ :href => new_car_path }
%span New Car
What you have is fine though..

If you're still curious, here are some ways to rewrite your code:
Use content_tag:
<%= link_to content_tag("span", "New car"), {:action => "new"}, :class=>"button" %>
Use link_to with a block:
<%= link_to {:action => "new"}, :class=>"button" do %>
<span>New card</span>
<% end %>
And of course, you can combine the two by putting a content_tag inside the block, but I'll leave it to the reader as an exercise :)

Related

adding a class to a link_to is breaking the link

I'm using link_to in RoR 3
When I use it like this, it works fine:
<%= link_to "Add to your favorites list",:controller =>
'favourite_companies', :action =>'create',
:company_id=>"#{#company.id}",
:company_name=>"#{#company.company_name}" %>
But I would like to pass in a class as well
however, this is not working for me. The class works, but it breaks the link. Any ideas?
<%= link_to "Add to your favorites list",{:controller =>
'favourite_companies', :action =>'create'},
:company_id=>"#{#company.id}",
:company_name=>"#{#company.company_name}",
:class=>"ui-button-text button_text"} %>
<%= link_to "Add to your favorites list",{:controller =>
'favourite_companies', :action =>'create'},
:company_id=>"#{#company.id}",
:company_name=>"#{#company.company_name}",
:class=>"ui-button-text button_text"} %>
try this
<%= link_to "Add to your favorites list", :controller =>
'favourite_companies', :action =>'create',
:company_id=>"#{#company.id}",
:company_name=>"#{#company.company_name}",
{ :class=>"ui-button-text button_text" } %>
Since the :class should be in :html_options (refering to API)
link_to(body, url, html_options = {})
The proper way of doing what you have is as follows:
link_to "Foo", { URL_FOR PARAMS HERE }, :class => "bar"
As far as setting the controller and action manually like this, well, it's crap. Rails builds url helpers for you; use them and save yourself some time, energy, and add clarity, all at once:
link_to "Foo", favourite_companies_path(#company), :method => :post
What you're doing with the string interpolation is a bad idea too…it's just wasteful and cluttered for no reason at all. The following is the same, just better:
link_to "Foo", :company_id => #company.id, :company_name => #company.name
As far as why your link wasn't working, if wrapping it in a div helped it sounds like you have a problem with your HTML structure, not the link_to syntax.
I'm using a link_to do-end block so the above previous solutions didn't work for me.
If you want to embed other tags in your a tag, then you can use the link_to do-end block.
<%= link_to favourite_companies_path(:company_id => #company.id, :another_url_param_here => "bar"), { :class => "ui-button-text button_text", :title=> "We can have more html attributes as well" } do %>
<i class="fa fa-star"></i>
<%= #company.company_name %>
<% end %>
In this case it's
<%= link_to path(url_params), html_options = {} do %>
<% end %>
Be careful because in Rails 5 the above methods will still result in a wrong URL generation. The controller and action need to be put in a literal hash in order for it to work in Rails 5. What you will have should be something like this
<%= link_to "Add to your favorites list",
{ controller: "favourite_companies", action:"create"},
company_id: #company.id,
company_name: #company.company_name,
class: "ui-button-text button_text" %>

Embedded HTML in link_to body in Rails

What is the best way to go about getting embedded HTML in the body of a link generated with the link_to method?
I basically want the following:
This is a <strong>link</strong>
I have been trying to go about this as suggested in Rails and the <span> tag but with no luck. My code looks like the following:
item_helper.rb
def picture_filter
#...Some other code up here
text = "Show items with " + content_tag(:strong, 'pictures')
link_to text, {:pics => true}, :class => 'highlight'
end
item_view.html.erb
#...
<%=raw picture_filter %>
#...
Try it this way
<%= link_to(raw("a <strong>strong</strong> link"),{:pics => true},{ :class => 'highlight'}) %>
= link_to "http://www.example.com" do
<strong>strong</strong>
As of 2016 I prefer this method.
<%= link_to my_path do %>
This is a <strong>ape</strong>
<% end %>
you can use html_safe
<%= link_to ("<i class='someIcon'></i> Link").html_safe %>
Not sure if this is the best way.
But I have been very successful in staking alot of the view helpers inside the content_tag call.
It also might not hurt to call a .html_safe
link_to(content_tag(:span, "Show yada " + content_tag(:strong, "Pictures")), {:pics => true})

Rails, how do you submit a form with a text link?

I am trying to get this form to submit correctly. Here's what I have so far:
<% form_for(:user, :url => update_user_setting_path, :remote => true, :html => {:method => :post, :class => "search_form general_form"}) do |f| %>
and the button renders with this code:
<li><%= link_to raw("<span class='button approve'><span><span>SAVE</span></span></span>"), :action => 'create' %></li>
I am using action create, is this correct?
Here is the rendered form tag:
<form method="post" data-remote="true" class="search_form general_form" action="/settings/2/update_user" accept-charset="UTF-8">
What am I missing? Thanks for your help!
No, you are not using link_to properly. You need to use a submit tag to submit your form, not a link_to tag, for example:
<% form_for(:user, :url => update_user_setting_path, :remote => true, :html => {:method => :post, :class => "search_form general_form"}) do |f| %>
...
<li><%= f.submit "Save" %></li>
If you want to use a text link you'll have to have javascript submit the form. For example, if you are using jQuery you could do the following:
<%= link_to 'Save', "#", :onclick=>"$('.search_form').submit()" %>
I like Pan's solution but I prefer to use the ID of the form directly which you can get from the dom_id(obj). The form_for helper also uses dom_id(obj) to assign the form's ID. This way you aren't dependent on setting classes by hand or subject to accidentally submitting more than one form that share the same CSS class. It looks a little stranger but I usually have a custom FormBuilder anyway so I just add a generic link_to_submit method to encapsulate this:
<%= link_to 'Save', "#", :onclick => "$('##{dom_id(#user)}').submit()" %>
You don't need to use an id or a selector if you have jquery, you can simply do :
= link_to 'Save', "#", onclick: "$(this).closest('form').submit()"
Thanks for the answers... I ended up using this and it works great:
<li><%= link_to raw("<span class='button approve'><span><span>SAVE</span></span></span>"), "index_users", :onclick=>"document.forms['form1'].submit();"%></li>

Rails: link_to image tag. how to add class to a tag

I am using link_to img tag like following
<%= link_to image_tag("Search.png", :border=>0, :class => 'dock-item'),
:action => 'search', :controller => 'pages'%><span>Search</span></a>
Which results in following html
<a href="/pages/search"><img alt="Search" border="0" class="dock-item"
src="/images/Search.png?1264132800" /></a><span>Search</span></a>
I want the class="dock-item" to go to the <a> tag instead of the img tag.
How can i change this?
Update:
<%= link_to image_tag("Search.png", :border=>0), :action => 'search',
:controller => 'pages', :class => 'dock-item' %>
results in
<a href="/pages/search?class=dock-item"><img alt="Search" border="0"
src="/images/Search.png?1264132800" /></a>
hi you can try doing this
link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}
or even
link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'
note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)
and according to the api for link_to:
link_to(name, options = {}, html_options = nil)
the first parameter is the string to be shown (or it can be an image_tag as well)
the second is the parameter for the url of the link
the last item is the optional parameter for declaring the html tag, e.g. class, onchange, etc.
hope it helps! =)
Just adding that you can pass the link_to method a block:
<%= link_to href: 'http://www.example.com/' do %>
<%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>
results in:
<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
<img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>
This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.
Best will be:
link_to image_tag("Search.png", :border => 0, :alt => '', :title => ''), pages_search_path, :class => 'dock-item'
this is my solution:
<%= link_to root_path do %>
<%= image_tag "image.jpg", class: "some class here" %>
<% end %>
Easy:
<%= link_to image_tag("Search.png", :border=>0), :action => 'search', :controller => 'pages', :class => 'dock-item' %>
The first param of link_to is the text/html to link (inside the a tag). The next set of parameters is the url properties and the link attributes themselves.
I tried this too, and works very well:
<%= link_to home_index_path do %>
<div class='logo-container'>
<div class='logo'>
<%= image_tag('bar.ico') %>
</div>
<div class='brand' style='font-size: large;'>
.BAR
</div>
</div>
<% end %>
To respond to your updated question, according to http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html...
Be careful when using the older argument style, as an extra literal hash is needed:
link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
# => Articles
Leaving the hash off gives the wrong link:
link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
# => WRONG!
The whole :action =>, :controller => bit that I've seen around a lot didn't work for me.
Spent hours digging and this method definitely worked for me in a loop.
<%=link_to( image_tag(participant.user.profile_pic.url(:small)), user_path(participant.user), :class=>"work") %>
Ruby on Rails using link_to with image_tag
Also, I'm using Rails 4.
Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)
<%= link_to image_tag("#{request.ssl? ? #image_domain_secure : #image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>
Hope this helps!
<%= link_to root_path do %><%= image_tag("Search.png",:alt=>'Vivek',:title=>'Vivek',:class=>'dock-item')%><%= content_tag(:span, "Search").html_safe%><% end %>
You can also try this
<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo" %></li>
Where "metas-logo" is a css class with a background image

How to create an anchor and redirect to this specific anchor in Ruby on Rails

I'm trying to create unique anchors for every comment on my blog so a person can take the url of an anchor and paste it in their browser, which will automatically load the page and scroll down to the point in the page where their comment starts.
Perhaps I'm going about this the wrong way but I've tried this which was to no avail.
Comment view - Fail 1 - when pasted in a browser this link does not scroll down to the desired position
<%= link_to '#', :controller => 'posts', :action => 'show', :id => comment.post, :anchor => 'comment_' << comment.id.to_s %>
Comments controller - Fail 2 - Correct url in browser but no scrolling happens it just stays at the top of the page
redirect_to :controller => 'posts', :action => 'show', :id => #post, :anchor => 'comment_' + #comment.id.to_s
If someone could help I'd be very grateful :)
UPDATE: The solutions below almost work, however I come out with the following URL which isn't being scrolled to if I click on it.
#
i.e. http://localhost:3000/posts/please-work
Actually, anchor is an option for the path, not for the link_to
<%= link_to '#', post_path(comment.post, :anchor => "comment_#{comment.id}") %>
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001565
link_to "Comment wall", profile_path(#profile, :anchor => "wall")
# => Comment wall
It looks like you want to use the link_to code that you have in your question. Then in your list of comments you have to make sure that you have an anchor tag named the same thing in the link.
So this:
<%= link_to 'Your comment', post_path(#comment.post) + "#comment_#{#comment.id.to_s}" %>
will generate something like this
Your comment
/* html code */
<a name="comment_1234">This is a comment</a>
You have to manually tack on the #comment_ otherwise the link_to method thinks that the :anchor attribute that you are passing it is for that tag.
Here's an improvement on #XGamerX's answer.
<%= link_to '#', [comment.post, { anchor: dom_id(comment) }] %>
Or
<%= link_to '#', post_path(comment.post, anchor: dom_id(comment)) %>
Try this:
<%= link_to '#', post_path(comment.post), :anchor => "comment_#{comment.id}" %>
this is best way:
<%= link_to '#', post_path(comment.post, anchor: dom_id(comment.id)) %>
These links will scroll down to position where you have code like:
<a name="comment_1"></a>
I don't know if there are helpers that will do it for you, but it is very simple and you can write your own.

Resources