updating the data records automatically in rails - javascript

I currently have User model that has the name attribute and am using ajax to grab selected data.
JS looks like this:
$("#save").click(function(){
var checkedUser = [];
$.each($("input[name='selected_user']:checked"), function(){
checkedUser.push($(this).val());
});
$.ajax({
type: "POST",
url: "/users/<%= current_user.id %>/friend",
data: {checked_user: checkedUser},
})
controller action:
def friend
user = User.find(params[:user_id])
checked_user = params[:checked_user]
#user = User.where(id: checked_user)
end
I want to build a function that updates the data records based on checkbox input and want to give time range.
For example, if there is a user and has a friends list and the user checks friend 'A' and submit, the friend A should not show on the user's friends list as checked as block for set time (could be 24hrs or 10hours) and once time's up, I want them back to the list again so it is like:
user -> set friend A as not to show for 10mins -> showing friend A as checked on the friend list -> after 10mins -> the friend A is showing again.
Q1) Should I make a new attribute that has boolean type then do update the attribute? or is there any better way to do this?
Q2) How to handle the times like if I wanted to uncheck the checked user after 10mins, should I use JS?

1) I would add two attributes, duration and checked_at, or maybe just one like expires_at. This will make #2 easier.
2) You will want to use a worker to schedule a periodic background job, using it to delete any entries that have expired.

Related

How to check changed columns in mysql

I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping

Rails real time database query marquee/ticker

Good day,
I would like to create a real time Newsticker/Marquee scroller for my rails app, Similar to what you would find on Sky Sports News TV channel.
I Need to be able to query the database table (which i can) and display the output in the ticker/marquee one table row at a time looping it over. Also i would like to either try display this query in real-time or very frequently and updating the output on the clients end without the page refreshing. (Similar to a chat room or twitter feed.)
Here is some basic code
Simple Query Which shows the subject and paper if the start time is < Current time and Stop time is > Current time
Model
Timetable.where("start < ? AND stop > ?", Time.now, Time.now).order('id ASC').pluck(:subject, :paper)
Html
<table><tbody><% #timetables.each do |timetable| %><tr><td><%= timetable[0] %></td><td>%= timetable[1] %></td></tr><% end %></tbody></table>
If anyone is able to hepl or point me in the right direction, Ill really appreciate it. Thanks
At the moment i could probably use a partial to display the query and update the partial, not sure if there is a better method using any gems that will open up an event listener or socket?
Interesting problem you've got here. Got me excited and I tried some things out myself!
If you want to have content refreshed on the client side (no page reload), you need to use javascript to repeatedly query the server. In Rails you'd probably go with a partial that's being rendered from both the page view and the API-view that's used in an AJAX call.
Let's assume you have a model called Item of which you want to show the latest 3 on your page and then fetch the latest every 5 seconds to update the page. You might want to create something that looks like the following:
controllers/content_controller.rb
class ContentController < ApplicationController
def show
end
end
views/content/show.haml
%h1 Page with updated items
.updateme
= render "items/latest"
controllers/items_controller.rb
class ItemsController < ApplicationController
layout false
def index
end
end
views/items/index.haml
= render "items/latest"
views/items/_latest.haml
- Item.last(3).each do |item|
= item.subject
Last but not least you will need to add javascript that calls the index for items
javascripts/update.js
function updateItems() {
$.ajax({
url: "/items",
}).done(function(data) {
$("div.updateme").html(data)
});
}
$( document ).ready(function() {
window.setInterval(function(){
updateItems();
}, 5000);
});
Hopefully this gets you started in the right direction :)

How to do an jQuery ajax call from a numberfield using Rails

I am doing a fixeddeposit project, in which I am having three models:
1)fixeddeposit
2)interestrate
3)interestsetup
When I open a fixeddeposit, I have to type the number of days(365/730/1095/1460 & 1825) from number_field. Then in another text box I want to update the rate_of_interest based upon the number(365/730/1095/1460 & 1825) I typed.
Rate_of_interest should be taken from rate which is in the interestrates table field. Kindly see the screenshot of my interestrates table below.
Interestrates table
Example:
If i type number 365 in fixeddeposit form(which is number_field). It automatically select rate 9.5% from interestrates table using AJAX function.
And, if a customer age is above 58, and i type number 365 in fixeddeposit form. It automatically select (rate 9.5% + senior increment 0.5% ) = 10.0% from interestrates table using AJAX function.
Screenshot of FD
I googled it for a solution but, results showing with collection_select alone. I want to do the same in number_field. Though, i am new to Ruby on Rails and AJAX i am struggling with it.
I see that the rate is dependent on Time Period and Date of Birth. So, one way to do it is to attach an event listener to the two input fields. So let's say, dob input field has id = dob, you can write simple jQuery to attach a listener like $("#dob").change()....
Now, inside the listener function, you update the value of Rate of Interest based on the values of Time Period and DOB. For this, you could write the ROI logic in the code or send an ajax request to Rails app and get Interest Rate from there.
Lets go through the steps of ajax in rails
a. Create a route for your custom action, since we want to send data so it'll be post request
post "/rate" => "your_controller#calculate_rate" , as: "calculate_rate"
b. Write a javascript code that will listen to your periods input field.
$(document).on("change","#id_of_periods_input",function(){
var periods = $(this).val();
var age = $("#id_of_age_input").val();
$.ajax({
type: "POST",
url: "/rate",
data: { periods: periods, age: age } //this will enable you to use params[:periods] and params[:age] in your controller
});
});
This will work but i think it'll be better if you have some sort of button and when user clicks on it then calculate your rate of interest because if you'll use on change event then then lets say your periods value is 365 so your ajax call will fire 3 times( first time when you enter 3 then for 6 and then for 5)
If you want to use button then also you have to use same logic only this line will change
$(document).on("click","#id_of_btn",function(){
// same logic
});
c. Getting your data in controller and performing your logic
def calculate_rate
#periods = params[:periods]
#age = params[:age]
// perform your logic here and store rates value in lets say #rate
respond_to do |format|
format.js{} #this will make rails look for a file named calculate_rate.js.erb in your views
end
end
d. Filling rates input field by writing js in calculate_rate.js.erb
$("#id_of_rate_field").val(#rate);

HTML form with intermediate web service service call before submit

I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).

Auto populate text_fields based on selected item from another collection_select in Rails 3

Hello people
I'm trying to figured this out, but I still can't do it.
I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.
I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start
hope you can help me... thanks
What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.
In your routes:
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
In your invoice_controller:
def get_json
invoice = Invoice.find(params[:invoice_id])
render :text => invoice.to_json
end
In your invoice model (if the default to_json method is not sufficent):
def to_json
json = "{"
json += "id:'#{self.id}'"
json += ",date_created:'#{self.date}'"
... //add other data you want to have here later
json += "}"
end
In your javascript file,
$("#invoice_selecter").change(function(){ //calls this function when the selected value changes
$.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){ //does ajax call to the invoice route we set up above
data = eval(data); //turn the response text into a javascript object
$("#field_1").val(data.date_created); //sets the value of the fields to the data returned
...
});
});
You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.

Categories