In Rails 3, how can you make a div a button (a clickable div that links to a new page) - ruby-on-rails-3

I know that there are options to do this manually, such as here : How do you make the entire DIV clickable to go to another page?
However, in Rails 3 we make links like this:
<%= link_to "name", url %>
And I am wondering -- is there a proper Rails way to make a whole div a button. I realize I could make a button. However, let's say I want to fill it with content like text and a picture - then how would I make that whole div clickable in a rails way?
For example:
<%= #story.title %>
<%= #story.blurb %>
In this example, I would want to make #story clickable, with the rails generated content that I specified.. Any ideas?

For those interested, the answer is:
<div class="class_name">
<%= link_to content_tag(:span, "Text for the LInk"), route %>
</div>
And then, in the CSS set .class_name to position:relative; and:
.class_name span {
width:100%;
height:100%;
position:absolute;
z-index:2;
top:0px;
left:0px;
}
The link will now assume the size of its parent container, and thus give the impression the whole container is a link.

I think that button_to is what you need :
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to

I might use jquery if you really wanted to do this
$(document).ready(function() {
$('#somediv').click(function(event){
document.location = 'http://someplace.com';
});
});
You can't make a "clickable" raw div like that in a rails way... the concept doesn't make any sense. That's just not how it works
(added missing close parens for click)
not tested

Related

How can I submit a form on input change with Turbo Streams?

I have a form I want to submit automatically whenever any input field is changed. I am using Turbo Streams, and if I use onchange: "this.form.submit()" it isn't captured by Turbo Streams and Rails uses a standard HTML response. It works fine when clicking the submit button. How can I work around this?
There is a discussion on the hotwire forum, where Mark Godwin figured out why form.submit() isn't working with turbo:
Turbo intercepts form submission events, but weirdly, the JS formElement.submit() method does not trigger the submit event.
And Jacob Daddario figures out that you can use form.requestSubmit() instead:
It turns out that the turbo-stream mechanism listens for form submission events, and for some reason the submit() function does not emit a form submission event. That means that it’ll bring back a normal HTML response. That said, it looks like there’s another method, requestSubmit() which does issue a submit event.
So you can change your code slightly, and use requestSubmit() if a browser supports it, and use submit() if not:
onchange: "this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()"
Update:
As BenKoshy pointed out, in Turbo 7.1.0, a polyfill was added so you can use form.requestSubmit() without checking for browser support, so you can add this to your input field:
onchange: "this.form.requestSubmit()"
I need to implement this for an app with lots of forms. I wound up using Stimulus. Below is the whole controller:
import { Controller } from "stimulus"
const _ = require("lodash")
export default class extends Controller {
connect() {
let that = this;
that.element.addEventListener('change', _.debounce(that.handleChange, 500))
}
handleChange(event) {
event.preventDefault()
// event.target.name // => "user[answer]"
// event.target.value // => <user input string>
event.target.form.requestSubmit()
}
}
and here it's used in a form with a single text input. NOTE the controller is attached to the form, not to the inputs.
<%= turbo_frame_tag dom_id(form_model) do %>
<%= form_with model: form_model,
format: :turbo_stream,
html: { data: { controller: "buttonless-form" } } do |f| %>
<%= f.hidden_field :question_id, value: question.id %>
<%= f.text_field :answer_value, class: "input shadow wide", placeholder: "Enter your answer here" %>
<% end %>
<div id=<%= "question_#{question.id}_output" %>>
<p> <!-- feedback to the user shows up here via Turbo -->
</div>
<% end %> <!-- end turbo frame -->

Re-using a stimulus action elsewhere on the page?

I am wiring up a slack clone (html/css) and have it so that the reference drawer opens/closes when I click on the x. I am wanting to also open/close it from the navigation area and thought I could just take the same link_to and call it from a different part of the page.
But when I do that, if I'm calling it from within a different target, I get an error
Error invoking action "click->navigation#toggle_reference_drawer"
Error: Missing target element "navigation.referenceDrawer"
How can I use code inside a data-target to trigger a different data-target?
i.e. what I'm trying to get working is
--navigation partial (link_to doesn't work) --
<div data-navigation-target="storyNavLinks">
<div class ="story">
<%= link_to "[x]", "#", data: { action: "click->navigation#hide_reference_drawer" } %>
</div>
</div>
-- application partial (link_to works) --
<div data-navigation-target="referenceDrawer">
<div class='reference box'>
<%= link_to "[x]", "#", data: { action: "click->navigation#hide_reference_drawer" } %>
</div>
</div>
Not sure where I'm going wrong.. I figured as long as the target being referenced is unique and on the page it shouldn't matter where it's being called from?
You have to make sure your data-controller attribute is on an element that wraps both targets. If that is not possible you can always include the controller twice but the targets will only be scoped to each instance so you will need to add them twice as well.

Jquery-ui datepicker with months and years menu rails

I have a rails app where I want to choose a date of birth. I'd like to use the jquery-ui datepicker for this but am not sure how to implement it into my rails app.
This is a screenshot of the options I want with the month and years menus to make selecting birthdates easier.
http://cl.ly/image/46152b372N1b
I'm really not sure where to start as far as setting this up in my application.js file as well as in my view.
Right now my view/form looks like this
<%= f.text_field :patient_dob, :id => 'datepicker' %>
Here's my application.js
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});
Again, I'd like that to be a a jquery-ui datepicker with the month and years option to make selecting the birthdate easier.
If anyone can throw me some code to get started, I'd appreciate it. Right now when I click the text field, nothing happens.
Make sure you include jquery.js, jquery-ui.js, jquery-ui.css in your head html tag.
jQuery and jQuery-ui javascript files should be declared only once. You can check this by right-clicking your webpage (eg. in chrome) and select View Source Code. Also, on Source Code click the jquery.js, jquery-ui.js, jquery-ui.css and application.js links and make sure that your code is in there (if you don't find the code expected, check your paths).
application.js file should be declared after jquery and jquery-ui.
So your < head > should look like this:
<head>
<meta [your code]>
<title>[your code]</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<%= javascript_include_tag "application.js" %>
</head>
After some searching and experimenting this code worked out for me. It seems what I was using before either wasn't the object or I had it closed wrong.
$(function(){
$('#datepicker').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1900:2013'
});
$('#datepicker').datepicker('option', 'dateFormat', 'yy-mm-dd');
});

rendering a partial Rails3.x + coffeescript

I have the following requirement. I have a 'school' drop down and as the last options I have add new school, so if the user selects that option I want to load the new_school form as a partial via ajax.
I'm on
gem 'rails', '3.2.9'
gem 'coffee-rails', '~> 3.2.1'
Jquery via gem 'jquery-rails'
Earlier with rails < 3 and prototype I used to do it with
Ajax.Updater (aka Rails link_to_remote :update => 'some_div')
and with rails > 3 + JQuery I'm familiar with *.js.erb, and having something like
$("#school_form").html("<%= escape_javascript(render(:partial => "form"))%>");
But I'm new to coffeescript and I have no idea on how to do this with coffeescript, can someone help me :), (because I believe you shouldn't have to do a server request for this)
So far I have done following to catch the select_tag change event
$ ->
$('#school_name_select').change ->
unless $(this).val()
$('school_name').html([I want to have the _new_school_form partial here])
Use a hidden div.
In general, you don't want to bother trying to mix JS and HTML. The escaping can be complicated, error-prone, and flat out dangerous due to the possibility of cross-site scripting attacks.
Simply render your form partial in a div that's not displayed by default. In ERB:
<div id="school_name_form" style="display: none;">
<%= render 'form' %>
</div>
In your CoffeeScript:
$ ->
$('#school_name_select').change ->
if $(this).val()
$('#school_name_form').slideUp()
else
$('#school_name_form').slideDown()
I recommend using a small, tasteful transition like slide or fade. It gives your app a more polished feel.
No AJAX is required. This pattern is so common that I have an application-wide style defined as follows.
.not-displayed {
display: none;
}
Then using HAML (if you're into that), the HTML template becomes simply:
#school_name_form.not-displayed
= render 'form'
You can try to render the form partial inside hidden div (not too correct from semantic point of view), or put the form html as data attribute of any relevant element, something like
f.select school_name, ... , data: {form: escape_javascript(render(:partial => "form"))}
And the Coffeescript
$ ->
$('#school_name_select').change ->
unless $(this).val()
$('school_name').html($('#school_name_select').data('form'))

Rails 3: how to render text file in-line?

All.
A Rails n00b here...
I'm writing an application that reports the status of a transaction.
Some of the content in the rendered HTML comes from instance variables
initialized in the controller, while other content comes from text files
(e.g., log files) that I want to render in the HTML using <pre> tags.
What is the "Rails Way" to do this?
Thank you for your time...
<pre>
<%= render :file => '/tmp/test.log' %>
</pre>
Here you go: http://edgeguides.rubyonrails.org/layouts_and_rendering.html
In some cases (when the file is not small and loading it is connected with a delay), I prefer to load the page content and then to use jQuery ajax request to load the file content.
For example, let's say I have a model with file path attribute. In the view layout I am doing something like this:
<pre data-source=" <%= (#file.path) %>"></pre>
Then in the corresponding js file I am loading the context like this:
$(document).ready ->
$.ajax(
url: $("pre").data("source")
context: document.body
).done (response) ->
$("pre").html response
return
return
Of course you can check the jQuery ajax documentation for more options. For example, you can render the pre tag with loading like this:
<pre data-source=" <%= (#file.path) %>"><div class="loading"></pre>
or use other jQuery animations as well.