How to get the foreign key column data when it is used in a select box - ruby-on-rails

I have this ruby on rails code
<%= builder.select(:serving_size_id, '') %>
I have not specified any options on purpose because I set the options in a different way when the page loads (using jQuery and Ajax).
The question: Is there any way I can get the value from the column "serving_size_id" but not change that line? I have a partial which I use it for new and edit and I think it would be sweet if I can do the setting of the selected index in JS.
Any ideas?

I'm not sure I completely understand your question, but if you want to set the value of the select field with JavaScript, you need to obtain the value in JavaScript at some point. I can think of two ways of doing this:
1) When you get the options via AJAX, have the server indicate which one is selected. This can be done by returning HTML <option> tags with selected="selected" set for one of them. To do this, your AJAX request is going to have to provide information about the object this select field is for (so the server can look up the object's current serving_size_id value).
2) When you render the field in your original partial, also render some JavaScript which sets the current value of the field, for example, underneath what you have above:
<%= javascript_tag "var ssid = '#{builder.object.serving_size_id}';" %>
Then, after the options are retrived via AJAX, the ssid variable is checked and the correct option is selected.

using jQuery in rails is easy but a little more difficult than prototype.
ex: "div id="serving_size" class="nice" rel="<%=h num%>">Stuff Goes Here.../div>"
in application.js do the following:
//application.js
$(document).ready(function(){
if($('#serving_size'){
$('#serving_size').live("mouseover",function(){
//we are hovering over specific div id serving size
if($('#serving_size').hasAttr('rel')){
alert($('#serving_size').attr('rel'); //your dynamic rel value, and fire function
}
}
}
if('.nice'){
$('.nice').live("mouseover",function(){
//we are now hovering over any item on page with class nice
if($(this).hasAttr('rel')){
//we are now using jQuery object ref and finding if that obj has attr rel
alert($(this).attr('rel')); // shows dynamic rel value
}
}
}
});
If you use the above code you should be able to do anything you want and fire any custom code from each of your set event callbacks.
The 'live' function in jQuery is great because it can be called on items that will eventually be on the page (eg. if you fill in something with ajax, jQuery will be prepared for that item being in the page)
I hope this help.

Related

Select & onChange | Ruby on Rails

In my view, I have this form with the select function:
<form id="form_id">
<%= form.select('id','name', #document.informations.find(:all).collect {|u| [u.name] },
options={},{:onChange => 'submit()'}) -%>
</form>
How can I use the selected name in the rest of my view ?
I saw this in other topics:
$('#id_name').val();
But it didn't work for me, it says:
`$(' is not allowed as a global variable name
You're getting that particular error because the $('#id_name').val() is JavaScript, not Ruby, but you've put it within erb tags.
When you visit a page /documents/3 in your browser, Rails will run the code in your controller, and send back some HTML to your browser. That HTML can load CSS and JavaScript, but that's run after your Ruby program has finished - and may not be run at all, depending on the browser. How you use the name of the selected item in your view depends on what you're doing with it.
If you're storing it in the database somewhere, then you should start by getting this working just in Ruby. For instance, if your #document has a selected_informations attribute, you could use that in the rest of your page, and pass it to your form.select to pre-select it in the page. The Rails Guides documentation has more info on this.
If you're not storing it in the database, then you can get the value of your box out with JavaScript whenever it changes. Here's some sample code that prints out the name of the selected item to the JavaScript console whenever a <select> box gets changed. I've included it in <script> tags so you can drop it straight into your view for testing, but you should put it into a dedicated JavaScript file if you adapt it for your project.
<script>
$('select').on('change', function(ev) {
var selected_item = $(ev.currentTarget).val();
console.log("Your select value is " + selected_item);
});
</script>
One final thing to note is that your existing form.select tag is set up to call a method submit() whenever its value gets changed. submit is just a name, so that function could do anything... but I'd guess it's submitting the form whenever an item is selected. This sends a request to your Rails server and refreshes the page, so beware - if you're using an event listener on change to update the current page, you won't see those changes on the new, refreshed page (and should use a server-side solution instead).

How do I pass the Value from a Dropdown Form through a Link in Rails?

I have a dropdown select on my page called language, which is in a form with other elements. When the form is submitted normally (which submits everything), I can access the value of the dropdown with params[:langauge].
I have another link/button on the page which, when clicked, should get the value of language and pass it to the controller. The controller could then run some ajax to change the language on the page. But how do I pass (just) the value of the dropdown through the link?
Update:
Should I get the value with Jquery, or is there a simpler way?
$('select[name="language"]').val()
If that is a link, the only way to use is query string
that link
You can get "href" of that link by JS, and then use this method to update query string.
Then the method will be able to process with correct params.
If that is a button, that would mean a mini form, you can set a hidden field inside the form and use jQuery to update its value. When sent, the controller method will know this value.
This javascript code should update the URL whenever the dropdown value is changed.
$(function() {
$('#link-button').attr("href", "/link_path/" +$(this).val())
$("select#language").change(function() {
$('#link-button').attr("href", "/link_path/" +$(this).val())
});
});

Ajax Dropdown Selection to change TextArea Contents

I'm trying to use Ajax in one of my Rails applications to have a form_tag textarea change its contents according to the selected value of a dropdown that is out of that form_tag.
I would like to ask, what is the correct way of handling this ? Is it possible to respond to js in my show action and have a js.rjs ? Do you happen to know of any resources or can offer some insight ?
You should write a javascript, which triggers on the dropdown menu's onchange event, and start an ajax process. With jQuery it is something like this (in your show code within a script tag):
$("#dropdownMenuName").change(function(){
$.get("controller/action.txt", function(data){ $("#textareaName").val(data); } );
});
This simply sends a request to your app on the controller/action.txt action, and the result is pasted into the textarea's text property. Of course you should write the answer as a simple text, as the result is printed in the textarea instantly.

How do I let data in 1 column power the content of the 2nd column in Rails 3?

Say I have a list of users in the left column, generated by <%= current_user.clients %> and the second column is empty by default.
However, when the user clicks on one of the links, the second column becomes populated with the projects associated with that user - without the entire page being reloaded (i.e. using AJAX).
I would also like to continue the process, so when they click on a project from that user, the third column is populated with other things (e.g. the name of images, etc.).
How do I accomplish this in Rails?
I assume you are using Rails 3 and jQuery (I'm not well-versed in prototype). It's easy to switch jQuery for prototype in Rails 3: https://github.com/rails/jquery-ujs
For the link:
Something
Using JavaScript and jQuery, write a function that sucks in links of class first_column_link (please rename to something more reasonable, by the way):
$(function() {
$('.first_column_link').bind('click', function() {
$.getJSON('/clients/' + $(this).attr('data-client-id'), function(data) {
// Populate the second column using the response in data
});
});
});
This doesn't work on browsers that don't support or have otherwise disabled JavaScript. Gracefully degrading would likely be a good idea, but without more context, I can't advise you how to best do it.
<%= link_to_remote current_user.clients, go_to_controller_path %>
Proceed from there.
go_to_controller_path routes to an action which renders javascript to update the 2nd column (probably with a partial).

How to Avoid Losing the State of Controls in ASP.NET MVC

I'm working with ASP.NET MVC 2 and building a simple business app. Here are some of the details:
The app deals with work orders and
has a work order index view. The
view has a table listing the work
orders, and several controls (text
boxes, check boxes, and drop down
lists) to select the criteria for
which work orders to display.
I'm using viewmodels. The work order
index view has a viewmodel with
properties for each and every
control.
I've implemented paging similar to
what is being done in the answer to
this question:
How do I do pagination in ASP.NET MVC?
I'm using LINQ's Skip() and Take() as
demonstrated, and ActionLinks for the
navigation.
If I load the page and don't
manipulate any of the controls, I can
click on the page number ActionLinks
and move around just fine between
pages of work orders. However, if I
change something, my changes are lost
when I navigate to another page.
For example, if I'm on page 1 and
click an unchecked check box, and
then click on the link for page 2,
the second page of results will load
but the check box will revert to its
previous state.
I understand why this happens, but I'm wondering what is the best thing to do from a design standpoint.
Potential solutions I can think of:
Set all the control values as route
values in the ActionLinks. This
seems really nasty, and could result
in very long URLs or query strings. Actually, now that I think of it this wouldn't work without a way to capture the control values.
Since ActionLinks don't post
anything, replace them with buttons.
Again, this seems like a bad idea.
Change the ActionLinks to links that
fire off a jQuery script that does a
POST. I think this is the most
promising option so far. Do many
developers do it this way?
This seems like a common enough problem, but none of these options feel quite right. I wonder if I'm missing something.
Can't you just save the changes back to the database when the user toggles the checkboxes (using jQuery):
$("input[type=checkbox]").click(function() {
$.ajax({
type: "POST",
url: "/ControllerName/SaveInfo?id=" + {id},
success: function(){
alert("Data Saved: " + msg);
}
});
});
In the end, I wound up getting rid of the ActionLinks for the paging, and replaced them with regular anchor tags. The current page index is now stored in a hidden form value:
<input id="page" name="page" type="hidden" value="" />
<p>
<% for (var i = 1; i <= (int)Math.Ceiling(Model.RowsMatchingCriteria / (double)Model.PageSize); i++) { %>
<%--
If the page number link being rendered is the current page, don't add the href attribute.
That makes the link non-clickable.
--%>
<a class="pageLink" <%= i != Model.Page ? #"href=""javascript:void(0);""" : string.Empty %>><%: i %></a>
<% } %>
</p>
Then I added the following jQuery script, which sets the hidden page value and submits the form when a link is clicked:
$(document).ready(function () {
$('.pageLink:[href]').click(function () {
$('#page').val($(this).text()); // Set hidden field value to the text of the page link, which is the page number.
$('form:first').submit();
});
});
Problem solved.
Best bet is to effectively simulate viewstate by "logging" the changes to a hidden field when a user paginates. To do so:
1) Figure out what data you need to capture and a data format to do so in {ie -- an array of json objects}
2) Setup the link that handles the prev/next to fire off a method to collect the "changed" things and stuff them into objects and into a hidden field.
3) When posting the form, parse the hidden field, extract data and profit.

Resources