image_to_function in Rails - ruby-on-rails

I have this method on rails so that I have an image calling a javascript function
def image_to_function(name, function, html_options = {})
html_options.symbolize_keys!
tag(:input, html_options.merge({
:type => "image", :src => image_path(name),
:onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
}))
end
I grabbed this code from the application helper of the redmine source code, the problem I'm having is that when I click on the image it's sending a POST, does some one know how can I stop that?
This is how I'm using it
<%= image_to_function "eliminar-icon.png", "mark_for_destroy(this, '.task')" %>
Thanks alot!

If your onclick event returns true, your browser follows the href, if it returns false, your browser won't follow. So here's the trick:
def image_to_function(name, function, html_options = {})
html_options.symbolize_keys!
tag(:input, html_options.merge({
:type => "image", :src => image_path(name),
:onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function}; return false;"
}))
end
Alternatively let #{function} return true or false and insert the return statement in front of the interpolation. This way the called function could control if the browser should follow the href.
PS: You probably want to replace tag(:input... with a link_to_function(image_path(name), ... construct so you can use it outside of forms, too.

Related

Passing params in a helper

I have, on my Miniature model view page the following code
<%= content_setmini_links_with_quantity(#miniature) %>
It refers to this miniatures_helper method
def content_setmini_links_with_quantity(miniature)
miniature.reverse_contents.map{|content| content_setmini_link_with_quantity(content)}.join(' ').html_safe
end
Which in turn references this miniatures_helper method
def content_setmini_link_with_quantity(content)
string = (tag "td"), (link_to top_pic(content.setmini_id), content.setmini), (link_to content.setmini.name, content.setmini)
string << " x#{content.quantity}" if content.quantity.present?
return string
end
This is supposed to reference the final miniatures_helper method
def top_pic
#miniature = Miniature.find(params[:setmini_id])
if #miniature.collections.first.photo != nil
image_tag(#miniature.collections.first.photo.url(:icon), :retina => true, :class => "curvediconminiset")
else
image_tag("https://system/stock/blank.gif", :retina => true, :class => "curvediconminiset")
end
end
but I can't work out how to call top_pic correctly.
As far as I can see in content_setmini_link_with_quantity(content) the only param available is content. Content.setmini_id is the param I want to use to find the #miniature to display but I can't get it to work.
Any help much appreciated.
You are calling
top_pic(content.setmini_id)
But your top_pic method definition does not have a parameter defined.
Change the definition and first line of top_pic to
def top_pic(setmini_id)
#miniature = Miniature.find(setmini_id)
and forget about using params in a helper.

html is being escaped in link_to

I'm trying to implement a link, when clicked marks you as present for a meeting. This link is a method in a helper:
def link_to_remote_registration(event_id)
down_image = "down_blanco.png"
up_image = "up_blanco.png"
unless registration.nil?
if registration.present == 1
up_image = "up_filled.png"
elsif registration.present == 0
down_image = "down_filled.png"
end
end
link_to_remote_registration = String.new
loading_and_complete = "Element.show('indicator_event_"+event_id.to_s+"'); Element.hide('vote_"+event_id.to_s+"')".html_safe
complete = "Element.hide('indicator_event_"+event_id.to_s+"'); Element.show('vote_"+event_id.to_s+"')".html_safe
link_to_remote_registration =
link_to(image_tag(up_image , :id => 'will_not_attend_event_'+ event_id.to_s , border => 0),
:url => new_registration_path(:present => 1, :event_id => event_id, :escape => false),
:remote => true,
:method => :put,
:loading => loading_and_complete,
:complete => complete)
return link_to_remote_registration
end
The problem is that when I render the link in my view some of the html gets escaped making the link not work.
<a href="/calendar?complete=Element.hide%28%27indicator_event_1%27%29%3B+Element.show%28%27vote_1%27%29&loading=Element.show%28%27indicator_event_1%27%29%3B+Element.hide%28%27vote_1%27%29&method=put&remote=true&url=%2Fregistrations%2Fnew%3Fevent_id%3D1%26present%3D1">
<img id="will_not_attend_event_1" border="0" src="/images/up_blanco.png?1198181114" alt="Up_blanco">
</a>
Which I think is not a valid url. I wonder why this happens - i call the html escape on the complete and loading string.
Regards
Since you're passing the html from from a helper, Rails sanitizes it to protect from XSS. You can override it by returning:
link_to_remote_registration.html_safe
http://railscasts.com/episodes/204-xss-protection-in-rails-3
You could also use raw() instead of disabling XSS system-wide.
raw(image_tag(up_image , :id => 'will_not_attend_event_'+ event_id.to_s , border => 0))

How to add additional params to a button_to form?

I want to have a Submit button. It updates one field on the submission; submission.state = :submitted
Now, I could make a custom route and a custom action and just post to that. But that seems really heavy-handed. Especially since I'll also have a reject button and possibly more. Needing a custom route & action for each of those seems downright silly to me.
It would be much nicer if I could do something like
button_to "Submit", submission_url(submission), :method => :put, :submission => { :state => :submitted }
Which would post to the submission's update method and update only the desired field.
But that doesn't work. How can I make it work? Or do you have a better idea of how to do this?
The pull request mentioned by #AugustinRiedinger has been merged and is now available as of Rails 4.1.0. Now just add the params option:
params: { state: :submitted }
It's not as concise, but without extending Rails, this will get me by:
= form_for submission, :html => { :class => "button_to" } do |f|
= f.hidden_field :state, :value => :submitted
= f.submit "Submit", :class => "link"
Add params:{} at the end, it will generate hidden_field
<%= button_to user.name, user, class:"btn btn-default", style:"", method: :patch, remote: true, params: { a_field: false, an_other_field:"a new value" } %>
I have something similar that works:
button_to "Submit", submission_url(submission, :submission => { :state => :submitted }), :method => :put
So, as from this rails pull request : https://github.com/rails/rails/pull/10471
Here is what you can do to have your custom button_to.
In application_helper.rb, add these lines:
module ApplicationHelper
// Unfortunately these 2 methods need to be redefined. I don't know how I could access the original ones.
def token_tag(token=nil)
if token != false && protect_against_forgery?
token ||= form_authenticity_token
tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
else
''
end
end
def method_tag(method)
tag('input', type: 'hidden', name: '_method', value: method.to_s)
end
def button_to_with_params(name = nil, options = nil, html_options = nil, &block)
html_options, options = options, name if block_given?
options ||= {}
html_options ||= {}
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w(disabled))
url = options.is_a?(String) ? options : url_for(options)
remote = html_options.delete('remote')
params = html_options.delete('params') { Hash.new }
method = html_options.delete('method').to_s
method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe
form_method = method == 'get' ? 'get' : 'post'
form_options = html_options.delete('form') || {}
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
form_options.merge!(method: form_method, action: url)
form_options.merge!("data-remote" => "true") if remote
request_token_tag = form_method == 'post' ? token_tag : ''
html_options = convert_options_to_data_attributes(options, html_options)
html_options['type'] = 'submit'
button = if block_given?
content_tag('button', html_options, &block)
else
html_options['value'] = name || url
tag('input', html_options)
end
inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
params.each do |name, value|
inner_tags.safe_concat tag(:input, type: "hidden", name: name, value: value.to_param)
end
content_tag('form', content_tag('div', inner_tags), form_options)
end
end
And to use it:
= button_to_with_params 'Awesome button', awesome_action_path, method: :put, :params => {:my_param => 'my_value'}
Enjoy! Have fun Railing!
If I read things correctly what you are effectively wanting to do something specific when a standard rails form is submitted in the standard way.
Notice that when a form is submitted using e.g.
f.submit "Save Changes"
then
params[:commit] = "Save Changes"
The GOOD thing about this is that it can allow you to do some appropriate branching in the controllers update action.
The BAD thing is that it's brittle. If one day you or someone else decides to change the button text, things break.. which is bad.
K
As of Rails 3.2.1 you can add additional params to the :html_options hash using the :form key.
http://apidock.com/rails/v3.2.1/ActionView/Helpers/UrlHelper/button_to
This did not exist prior to 3.2.1 so the more verbose solution of declaring a form with hidden attributes was required.

How can I make the html output from button_to have single quotes instead of double?

I've got this line:
<%= button_to 'Post', newpost_path(:type => 'short_note') %>
which outputs this:
<form method="post" action="/posts/newpost?type=short_note" class="button-to"><div><input type="submit" value="Add" /></div></form>;
But I need the output to have single quotes, not double. How can I do this?
<form method='post' action='/posts/newpost?type=short_note' class='button-to'><div><input type='submit' value='Add' /></div></form>;
Try this:
<%= (button_to 'Post', newpost_path(:type => 'short_note')).gsub('"', '\'') %>
create a file in rails_root/lib called url_helper_overrides.rb that simply overrides the button to method. Or you could add the button_to method below to your application_helper. This method is taken straight from the UrlHelper source in Rails (Github Link), I simply replaced the double quotes with single quotes.
module ActionView
module Helpers
module UrlHelper
def button_to(name, options = {}, html_options = {})
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w( disabled ))
method_tag = ''
if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)
end
form_method = method.to_s == 'get' ? 'get' : 'post'
remote = html_options.delete('remote')
request_token_tag = ''
if form_method == 'post' && protect_against_forgery?
request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
end
url = options.is_a?(String) ? options : self.url_for(options)
name ||= url
html_options = convert_options_to_data_attributes(options, html_options)
html_options.merge!("type" => "submit", "value" => name)
("<form method='#{form_method}' action='#{html_escape(url)}' #{"data-remote='true'" if remote} class='button_to'><div>" +
method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
end
end
end
end
I think the only way is to gsub(/"/, "'") but this is really ugly

Rails Button, remote_function. Possible without Ajax?

I want to create a very simple search partial. It has a text box, to query, and search db. Can I create a remote_function call without using AJAX or JS? Can I keep it entirely "Rails-ee"?
<%= text_field_tag "search_term",'', :size => 10 %>
<%= button "search", :onclick => remote_function( :url => {:action => :fill_in_lots },
:with => "search_term" ) %>
This isn't a problem, you need to use a technique called formal link. Instead of button you put a from with submit button. Below is a code of helper I use for this:
def formal_link_to(*args, &block)
options = html_options = name = nil
if block_given?
options = args.first
html_options = args.second
name = capture(&block)
else
name = args.first
options = args.second || {}
html_options = args.third
end
method = html_options.delete(:method) || "POST"
method = method.to_s.upcase
url = url_for(options)
html = "<form class=\"formal-link\" action=\"#{url}\" method=\"post\">"
html += "<input type=\"hidden\" value=\"#{form_authenticity_token}\" name=\"authenticity_token\" />"
html += "<input type=\"hidden\" value=\"#{method}\" name=\"_method\" />"
html += link_to(name, "#", html_options)
html += "</form>"
if block_given?
concat(html)
else
return html
end
end
You use this helper like a normal link_to, but you can pass extra options :method in second hash. Example:
<%= formal_link_to "Fill in lots", { :action => "fill_in_lots" }, { :method => :post } -%>
Remarks:
1. This of course will make the full page reload, but it is inevitable without using JavaScript.
2. I assumed action fill_in_lots is exposed to POST request. In case of GET you can use normal link_to helper.

Resources